Invia email tramite MailGun e SendGrid in Java

Invio di messaggi usando MailGun e SendGrid

Aspose.Email fornisce un’API unificata per inviare messaggi email utilizzando i servizi MailGun o SendGrid. L’API consente di inizializzare un client, preparare e inviare il messaggio email.

Prima di tutto, è importante configurare le opzioni a seconda del servizio che verrà usato per inviare i messaggi. Con il DeliveryServiceOptions classe, imposta i parametri di DeliveryServiceClient. Il seguente esempio di codice ti mostrerà come configurare le opzioni per i servizi.

Opzioni client MailGun:

String domain = "YOUR_MAILGUN_DOMEN";
String privApiKey = "YOUR_MAILGUN_PRIVATE_API_KEY";
MailgunClientOptions opt = new MailgunClientOptions();
opt.setDomain(domain);
opt.setApiKey(privApiKey);

Opzioni client SendGrid:

String privApiKey = "YOUR_SENDGRID_PRIVATE_API_KEY";
SendGridClientOptions opt = new SendGridClientOptions();
opt.setApiKey(privApiKey);

Quindi, chiama l’istanza del client necessaria usando il builder.

IDeliveryServiceClient client = DeliveryServiceClientFactory.get(opt);

Infine, prepara e invia un messaggio email.

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