Spring Bootでメールを送信する

Gmailを使用してメールを送信します。

アプリパスワードを作成する

2段階認証を使用する場合は、最初にアプリパスワードを作成します。

アプリパスワードを作成する

依存JARファイルを取得する

Java MailJavaBeans Activation Frameworkをダウンロードします。

依存関係を追加する

build.gradle

dependencies {
    compile 'org.springframework.boot:spring-boot-starter'
+   compile 'org.springframework.boot:spring-boot-starter-mail'
+   compile fileTree(dir: 'libs', include: '*.jar')
}

フォルダー構成

|-build.gradle
|-libs/
|  |-activation.jar
|  `-javax.mail.jar
`-src/

コードの作成

application.properties

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=<Gmailアカウント>
spring.mail.password=<パスワード>
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

2段階認証を使用する場合はアプリパスワードを設定します。それ以外の場合は通常のログインパスワードを設定します。

Main.java

package sample.springboot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

@SpringBootApplication
public class Main {

    public static void main(String[] args) {
        try (ConfigurableApplicationContext ctx = SpringApplication.run(Main.class, args)) {
            ctx.getBean(Main.class).sendMail();
        }
    }

    @Autowired
    private MailSender sender;

    public void sendMail() {
        SimpleMailMessage msg = new SimpleMailMessage();

        msg.setFrom("test@mail.com");
        msg.setTo("送信先メールアドレス");
        msg.setSubject("Send mail from Spring Boot");
        msg.setText("Spring Bootからメールを送信できます。");

        this.sender.send(msg);
    }
}

受信結果を確認する

送信先のメールボックスを開き、受信したメッセージを確認します。