Надсилання повідомлень за допомогою SendGrid Service Client у Java
SendGridClient з com.aspose.email.services.sendgrid.client пакет надсилає повідомлення через SendGrid Web API. Клієнт підключається по HTTP. Щоб дізнатися, як обрати HTTP‑бібліотеку, дивіться HTTP‑клієнти для поштових сервісів.
Цей клієнт працює зі власною моделлю даних. Щоб надіслати MailMessage через SendGrid, дивіться Відправка електронної пошти через MailGun та SendGrid.
Надсилання повідомлення
Щоб створити клієнта, передайте ваш API‑ключ SendGrid у будівельник. Використовуйте SendGridMessage.create щоб підготувати повідомлення з одним одержувачем і HTML‑тілом, а потім передати його до mailSend().send:
import com.aspose.email.services.sendgrid.client.SendGridClient;
import com.aspose.email.services.sendgrid.model.SendGridMessage;
try (SendGridClient sendGrid = SendGridClient.builder().apiKey("api-key").build()) {
SendGridMessage message = SendGridMessage.create(
"from@example.com", "to@example.com", "Weekly report", "<p>The report is ready.</p>");
String messageId = sendGrid.mailSend().send(message);
System.out.println(messageId);
}
The send метод повертає значення X-Message-Id заголовок відповіді, або null якщо клієнт не знайде цей заголовок у відповіді. Інші приклади коду на цій сторінці використовують sendGrid змінну, створену тут.
Встановлення одержувачів та вмісту
Щоб встановити кілька одержувачів, імена відображення та текстовий і HTML‑вміст, зберіть повідомлення з його частин. Одержувачі згруповані у SendGridPersonalization об’єкт:
import com.aspose.email.services.sendgrid.model.SendGridAddress;
import com.aspose.email.services.sendgrid.model.SendGridContent;
import com.aspose.email.services.sendgrid.model.SendGridMessage;
import com.aspose.email.services.sendgrid.model.SendGridPersonalization;
SendGridPersonalization recipients = new SendGridPersonalization("to@example.com", "Recipient Name");
recipients.addCc(new SendGridAddress("cc@example.com"));
recipients.addBcc(new SendGridAddress("bcc@example.com"));
SendGridMessage message = new SendGridMessage();
message.setFrom(new SendGridAddress("from@example.com", "Reports Team"));
message.setReplyTo(new SendGridAddress("reply@example.com"));
message.setSubject("Weekly report");
message.addPersonalization(recipients);
message.addContent(SendGridContent.text("The report is ready."));
message.addContent(SendGridContent.html("<p>The report is <b>ready</b>.</p>"));
sendGrid.mailSend().send(message);
Додавання вкладень
SendGridAttachment.fromBytes створює вкладення з даних файлу, назви файлу та типу вмісту:
import com.aspose.email.services.sendgrid.model.SendGridAttachment;
import com.aspose.email.services.sendgrid.model.SendGridMessage;
import java.nio.file.Files;
import java.nio.file.Paths;
byte[] data = Files.readAllBytes(Paths.get("report.pdf"));
SendGridMessage message = SendGridMessage.create(
"from@example.com", "to@example.com", "Weekly report", "<p>The report is attached.</p>");
message.addAttachment(SendGridAttachment.fromBytes(data, "report.pdf", "application/pdf"));
sendGrid.mailSend().send(message);
Використання динамічних шаблонів
Щоб надіслати повідомлення за динамічним шаблоном, встановіть ID шаблону і передайте дані шаблону через SendGridPersonalization:
import com.aspose.email.services.sendgrid.model.SendGridAddress;
import com.aspose.email.services.sendgrid.model.SendGridMessage;
import com.aspose.email.services.sendgrid.model.SendGridPersonalization;
import java.util.HashMap;
import java.util.Map;
Map<String, Object> data = new HashMap<String, Object>();
data.put("name", "Recipient Name");
SendGridPersonalization recipients = new SendGridPersonalization("to@example.com");
recipients.setDynamicTemplateData(data);
SendGridMessage message = new SendGridMessage();
message.setFrom(new SendGridAddress("from@example.com"));
message.setTemplateId("d-1234567890");
message.addPersonalization(recipients);
sendGrid.mailSend().send(message);
Планування повідомлення та додавання категорій
Щоб запланувати доставку, передайте Unix‑таймстамп у секундах до setSendAt. Щоб групувати повідомлення у статистиці SendGrid, додавайте категорії за допомогою addCategory:
import com.aspose.email.services.sendgrid.model.SendGridMessage;
SendGridMessage message = SendGridMessage.create(
"from@example.com", "to@example.com", "Weekly report", "<p>The report is ready.</p>");
message.setSendAt(System.currentTimeMillis() / 1000 + 3600);
message.addCategory("reports");
sendGrid.mailSend().send(message);
Обробка помилок
Коли SendGrid повертає помилковий статус, клієнт генерує HttpClientException, що містить статус і тіло відповіді. Виняток розширює java.io.IOException, яку клієнт також генерує при збоях підключення.
import com.aspose.email.services.sendgrid.client.SendGridClient;
import com.aspose.email.services.sendgrid.model.SendGridMessage;
import com.aspose.ext.http.HttpClientException;
try (SendGridClient sendGrid = SendGridClient.builder().apiKey("invalid-api-key").build()) {
sendGrid.mailSend().send(SendGridMessage.create(
"from@example.com", "to@example.com", "Weekly report", "<p>The report is ready.</p>"));
} catch (HttpClientException e) {
System.out.println(e.getStatusCode() + ": " + e.getResponseBody());
}