この内容は古いバージョンです。最新バージョンを表示するには、戻るボタンを押してください。
バージョン:2
更新日時:2019-03-07 07:12:53
タイトル: Spring BootでGmailからメール送信
SEOタイトル: Spring BootでGmailからメール送信する方法
| この記事の要点 |
- Spring Boot からGmail SMTP 経由でメール送信する手順
- 依存:
spring-boot-starter-mail を pom.xml に追加
- 設定:
application.properties で spring.mail.host=smtp.gmail.com / port=587 / username / password
- Google アカウント側でアプリパスワード生成が必要(2 段階認証必須)
|
前提
・Spring Boot 2
・mavenを使用(gradleでも読み替えれば可)
・Googleアカウント作成済み
ライブラリの追加
pom.xmlに以下の記述を追加する。
|
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
|
プロパティの設定
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
|
passwordにはアプリ用のパスワードを発行して設定する必要がある。
アプリパスワードの発行
こちらの公式ドキュメントを参考にアプリパスワードを発行する。
メールの送信
以下、バッチアプリでのメール送信例。
|
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
@SpringBootApplication
@EnableBatchProcessing
public class SampleApplication implements CommandLineRunner{
@Autowired
MailSender mailSender;
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setFrom("送信元のアドレスを記述");
msg.setTo("送信先のアドレスを記述");
msg.setSubject("タイトルを記述");
msg.setText("本文を記述");
this.mailSender.send(msg);
}
}
|
本文の改行
本文内で改行する場合は「\r\n」と記述すれば良い。