Mengirim Pesan Menggunakan Klien Layanan SendGrid di Java

SendGridClient dari com.aspose.email.services.sendgrid.client paket mengirim pesan melalui API Web SendGrid. Klien terhubung lewat HTTP. Untuk mempelajari cara memilih perpustakaan HTTP, lihat Klien HTTP untuk Layanan Mail.

Klien ini bekerja dengan model data miliknya sendiri. Untuk mengirim sebuah MailMessage melalui SendGrid, lihat Kirim Email via MailGun dan SendGrid.

Mengirim Pesan

Untuk membuat klien, berikan kunci API SendGrid Anda ke builder. Gunakan SendGridMessage.create untuk menyiapkan pesan dengan satu penerima dan badan HTML, lalu berikan ke 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 metode mengembalikan nilai X-Message-Id header respons, atau null jika klien tidak dapat menemukan header ini dalam respons. Contoh kode lain pada halaman ini menggunakan sendGrid variabel yang dibuat di sini.

Mengatur Penerima dan Konten

Untuk mengatur beberapa penerima, nama tampilan, dan konten teks serta HTML, bangun pesan dari bagiannya. Penerima dikelompokkan dalam sebuah SendGridPersonalization objek:

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

Menambahkan Lampiran

SendGridAttachment.fromBytes membuat lampiran dari data file, nama file, dan tipe konten:

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

Menggunakan Templat Dinamis

Untuk mengirim pesan berdasarkan templat dinamis, atur ID templat dan berikan data templat melalui 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);

Menjadwalkan Pesan dan Menambahkan Kategori

Untuk menjadwalkan pengiriman, berikan cap waktu Unix dalam detik ke setSendAt. Untuk mengelompokkan pesan dalam statistik SendGrid, tambahkan kategori dengan 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);

Menangani Kesalahan

Ketika SendGrid mengembalikan status error, klien melempar HttpClientException, yang berisi status dan tubuh respons. Pengecualian ini memperluas java.io.IOException, yang juga dilempar klien untuk kegagalan koneksi.

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