Sending Messages Using the SendGrid Service Client in Java

SendGridClient from the com.aspose.email.services.sendgrid.client package sends messages through the SendGrid Web API. The client connects over HTTP. To learn how to select an HTTP library, see HTTP Clients for Mail Services.

This client works with its own data model. To send a MailMessage through SendGrid, see Send Email via MailGun and SendGrid.

Sending a Message

To create a client, pass your SendGrid API key to the builder. Use SendGridMessage.create to prepare a message with one recipient and an HTML body, and then pass it to 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 method returns the value of the X-Message-Id response header, or null if the client cannot find this header in the response. Other code samples on this page use the sendGrid variable created here.

Setting Recipients and Content

To set several recipients, display names and both text and HTML content, build the message from its parts. The recipients are grouped in a SendGridPersonalization object:

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

Adding Attachments

SendGridAttachment.fromBytes creates an attachment from the file data, the file name and the content type:

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

Using Dynamic Templates

To send a message based on a dynamic template, set the template ID and pass the template data through 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);

Scheduling a Message and Adding Categories

To schedule delivery, pass a Unix timestamp in seconds to setSendAt. To group messages in SendGrid statistics, add categories with 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);

Handling Errors

When SendGrid returns an error status, the client throws HttpClientException, which contains the status and the response body. The exception extends java.io.IOException, which the client also throws for connection failures.

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());
}