1. mail starterを追加する
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2. application.propertiesでSMTPを設定する
spring.mail.host=smtp.sendcorex.com
spring.mail.port=587
spring.mail.username=${SENDCOREX_API_KEY}
spring.mail.password=${SENDCOREX_API_KEY}
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
キーはリポジトリではなく、必ず環境変数に置きましょう。
3. プレーンテキストのメールを送る
@Service
public class MailService {
private final JavaMailSender mailer;
public MailService(JavaMailSender mailer) { this.mailer = mailer; }
public void sendWelcome(String to) {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setFrom("Acme <hello@yourdomain.com>");
msg.setTo(to);
msg.setSubject("Welcome to Acme");
msg.setText("Thanks for signing up!");
mailer.send(msg);
}
}
4. HTMLを送る
MimeMessage mime = mailer.createMimeMessage();
MimeMessageHelper h = new MimeMessageHelper(mime, true, "UTF-8");
h.setFrom("hello@yourdomain.com", "Acme");
h.setTo(to);
h.setSubject("Your receipt");
h.setText("Your receipt is attached.", "<html><body><p>Your receipt is attached.</p></body></html>");
mailer.send(mime);
プレーンテキスト版とHTML版の両方を渡し、HTMLは<html>と<body>タグのある完全なドキュメントとして送りましょう。断片だけのHTMLはよくあるスパムのシグナルです。
5. ドメインを認証する
本番公開の前に、Sendcorexにドメインを追加し、表示されるSPF、DKIM、DMARCレコードを公開してください。すべてのメールで、ブランドと一致する同じ送信者名を使いましょう。SPFジェネレーターとDMARCジェネレーターでレコードを作成できます。