SpringBoot + Amazon SESでメール発送

2023/07/23に公開

前提条件

  • AWS会員である事
  • AWS SESにmailが登録されている事

Java SDKでメール発送

Security Credentials発行

iam
IAMにて「自分の認証情報」をクリック
access-key
アクセスキーを作成し「Download key File」をクリックしcsvファイルをダウンロードする。

csvファイルを開くと中にAWSAccessKeyIdAWSSecretKeyが記載されている。
この二つの値がAWS SESを使用するときに必要な認証キーである。
AWS SDKが読み込めるようにCredentialsを作る。

vi ~/.aws/credentials
credentials
[default]
aws_access_key_id=AWSAccessKeyId値
aws_secret_access_key=AWSSecretKey値

mfa認証を使用している場合

credentials
[default]
aws_access_key_id=AWSAccessKeyId値
aws_secret_access_key=AWSSecretKey値
mfa_serial = iamに記載されているmfa番号

これで設定は終わりです。

実際に送ってみる

  • spring boot 2.7.3
  • gradle使用

build.gradleにAWS SDKを追加

build.gradle
implementation group: 'com.amazonaws', name: 'aws-java-sdk-ses'

メール発送用VOを生成

MailVO.java
@Getter
public class MailVo {
  private final String from;
  private final String subject;
  private final String to;
  private final String cc;
  private final byte[] file;
  private final String fileName;

  @Builder
  public MailVo(
	  String from,
	  String subject, 
	  String to, 
	  String cc, 
	  byte[] file, 
	  String fileName) {
    this.from = from;
    this.subject = subject;
    this.to = to;
    this.cc = cc;
    this.file = file;
    this.fileName = fileName;
  }
  
  public SendRawEmailRequest toSendRawEmailRequest() throws MessagingException, IOException {  
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
      MimeMessage mimeMessage = createMimeMessage();
      mimeMessage.writeTo(outputStream);

      return new SendRawEmailRequest()
              .withRawMessage(new RawMessage(ByteBuffer.wrap(outputStream.toByteArray())));
    }
  }
  
  private MimeMessage createMimeMessage() throws MessagingException, UnsupportedEncodingException {
    Session session = Session.getDefaultInstance(new Properties());

    MimeMessage message = new MimeMessage(session);
    MimeMessageHelper helper = new MimeMessageHelper(message, true, StandardCharsets.UTF_8.name());

    if (Strings.isNotEmpty(this.cc)) {
      helper.setCc(this.cc);
    }
    helper.setTo(this.to);
    helper.setText("htmlまたはtemplate入れられる。", true);
    helper.setSubject(this.subject);
    helper.setFrom(this.from, "personalオプション");
    // ファイルがあれば添付
    if (!Objects.isNull(this.file) && !Objects.isNull(this.fileName)) {
      helper.addAttachment(this.fileName, new ByteArrayResource(this.file));
    }

    return message;
  }
}

mail発送用Serviceを作成

  • sendRawEmailを使った理由はファイルも一緒に添付できるようにするためです。
MailService.java
@Service
@RequiredArgsConstructor
public class MailService {

  private final AmazonSimpleEmailService awsMail;
  
}

public void sendEmail(MailVo mailVo) throws MessagingException, IOException {
  awsMail.sendRawEmail(mailVo.toSendRawEmailRequest());
}

発送する時は

MailController.java
  MailVo mail = MailVo.builder()
    .from("testFrom@test.com")
    .subject("タイトル")
    .to("testTo@java.com")
    .build();

  try {
    mailService.sendEmail(mail);
  } catch (MessagingException | IOException e) {
    log.error(e.getLocalizedMessage());
  }

Discussion