Java에서 SendGrid 서비스 클라이언트를 사용한 메시지 전송

SendGridClient 에서 확인하세요 com.aspose.email.services.sendgrid.client 패키지는 SendGrid 웹 API를 통해 메시지를 전송합니다. 클라이언트는 HTTP를 통해 연결합니다. HTTP 라이브러리 선택 방법은 메일 서비스용 HTTP 클라이언트.

이 클라이언트는 자체 데이터 모델을 사용합니다. 보내려면 MailMessage SendGrid를 통해 전송하려면, 참고 MailGun 및 SendGrid를 통한 이메일 전송.

메시지 전송

클라이언트를 만들려면 SendGrid API 키를 빌더에 전달하십시오. 사용법은 SendGridMessage.create 하나의 수신자와 HTML 본문을 가진 메시지를 준비하고 이를 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);
}

다음은 send 메서드는 X-Message-Id 응답 헤더를 사용하거나 null 클라이언트가 응답에 이 헤더를 찾지 못한 경우. 이 페이지의 다른 코드 샘플은 sendGrid 여기서 만든 변수입니다.

수신자 및 콘텐츠 설정

여러 수신자, 표시 이름 및 텍스트와 HTML 콘텐츠를 설정하려면 메시지를 파트별로 구성하십시오. 수신자는 SendGridPersonalization 객체:

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

첨부 파일 추가

SendGridAttachment.fromBytes 파일 데이터, 파일 이름 및 콘텐츠 타입으로부터 첨부 파일을 생성합니다:

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

동적 템플릿 사용

동적 템플릿을 사용해 메시지를 보내려면 템플릿 ID를 설정하고 템플릿 데이터를 통해 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);

메시지 일정 잡기 및 카테고리 추가

전송 일정을 잡으려면 Unix 타임스탬프(초)를 setSendAt. SendGrid 통계에서 메시지를 그룹화하려면 카테고리를 추가하십시오: 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);

오류 처리

SendGrid가 오류 상태를 반환하면 클라이언트는 HttpClientException, 상태와 응답 본문을 포함합니다. 이 예외는 java.io.IOException, 클라이언트가 연결 실패 시에도 던지는 예외입니다.

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