Invio di Messaggi con il Client di Servizio SendGrid in Java

SendGridClient dal com.aspose.email.services.sendgrid.client pacchetto invia messaggi tramite l’API Web di SendGrid. Il client si connette via HTTP. Per imparare a scegliere una libreria HTTP, vedi Client HTTP per i servizi di posta.

Questo client funziona con il proprio modello di dati. Per inviare un MailMessage tramite SendGrid, vedi Invia Email via MailGun e SendGrid.

Invio di un Messaggio

Per creare un client, passa la tua chiave API SendGrid al builder. Usa SendGridMessage.create per preparare un messaggio con un destinatario e un corpo HTML, e poi passarlo a 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);
}

Il send il metodo restituisce il valore del X-Message-Id header di risposta, o null se il client non trova questo header nella risposta. Altri esempi di codice in questa pagina usano il sendGrid variabile creata qui.

Impostazione Destinatari e Contenuto

Per impostare più destinatari, nomi visualizzati e contenuti testuali e HTML, costruisci il messaggio dalle sue parti. I destinatari sono raggruppati in un SendGridPersonalization oggetto:

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

Aggiunta di allegati

SendGridAttachment.fromBytes crea un allegato dai dati del file, nome file e tipo di contenuto:

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

Uso di Modelli Dinamici

Per inviare un messaggio basato su un modello dinamico, imposta l’ID del modello e passa i dati del modello tramite 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);

Programmazione di un Messaggio e Aggiunta di Categorie

Per programmare la consegna, passa un timestamp Unix in secondi a setSendAt. Per raggruppare i messaggi nelle statistiche di SendGrid, aggiungi categorie con 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);

Gestione degli errori

Quando SendGrid restituisce uno stato di errore, il client lancia HttpClientException, che contiene lo stato e il corpo della risposta. L’eccezione estende java.io.IOException, che il client lancia anche per errori di connessione.

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