在 Java 中通过 MailGun 和 SendGrid 发送电子邮件
Contents
[
Hide
]
使用 MailGun 和 SendGrid 发送消息
Aspose.Email 提供统一的 API,以使用 MailGun 或 SendGrid 服务发送电子邮件。该 API 允许您初始化客户端,准备并发送电子邮件。
首先,重要的是根据将要使用的发送服务设置选项。使用 DeliveryServiceOptions class,设置 DeliveryServiceClient 参数。以下代码示例将展示如何为服务设置选项。
MailGun 客户端 选项:
String domain = "YOUR_MAILGUN_DOMEN";
String privApiKey = "YOUR_MAILGUN_PRIVATE_API_KEY";
MailgunClientOptions opt = new MailgunClientOptions();
opt.setDomain(domain);
opt.setApiKey(privApiKey);
SendGrid 客户端 选项:
String privApiKey = "YOUR_SENDGRID_PRIVATE_API_KEY";
SendGridClientOptions opt = new SendGridClientOptions();
opt.setApiKey(privApiKey);
然后,使用构建器调用所需的客户端实例。
IDeliveryServiceClient client = DeliveryServiceClientFactory.get(opt);
最后,准备并发送电子邮件。
MailMessage eml = new MailMessage("fromAddress", "toAddress", "subject", "body");
DeliveryServiceResponse resp = client.send(eml);
if (!resp.isSuccessful()) {
for (String error : resp.getErrorMessages()) {
System.out.println(error);
}
}