使用 Java 中的 SendGrid 服务客户端发送消息

SendGridClient 自 com.aspose.email.services.sendgrid.client 包通过 SendGrid Web API 发送消息。客户端通过 HTTP 进行连接。要了解如何选择 HTTP 库,请参见 邮件服务的 HTTP 客户端.

此客户端使用其自己的数据模型。要发送 MailMessage 通过 SendGrid,参见 通过 MailGun 和 SendGrid 发送电子邮件.

发送消息

要创建客户端,请将您的 SendGrid API 密钥传递给构建器。使用 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);
}

该 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);

安排消息和添加分类

要安排投递,请向 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());
}