【コピペでOK】Spring Boot を使用してGmailからメールを送信する方法
0. はじめに
今回は、タイトルの通り、Spring Boot を使用してGmailからメールを送信したいケースがありました。
ネットの情報を見ながらやったのですが、情報が足りずに詰まってしまったため、皆さんに共有しようと思いました。
今回はKotlinという言語を使用していますが、Javaと似ているため、Java開発者も容易に理解できると思います。
1. 前提
今回は、以下の構成でプログラムを記述しています。
また、ビルドシステムにはgradleを使用していますので、
mavenユーザーは適宜読み替えをお願いします。
1 2 3 |
java : 1.8 kotlin : 1.3.61 Spring Boot : 2.2.4.RELEASE |
2. 実装に必要なこと
今回の実装で必要なことは以下の4点です。
- Google上での作業
- 依存性の追加 (gradleファイルへの記述)
- application.yml ファイルへの定義追加
- メール送信クラスの作成
では、順番に説明を実施していきます。
3. Google上での作業
Googleでは、セキュリティの観点で "アプリ パスワード" と呼ばれるものが必要です。
そして、 "アプリ パスワード" を取得する前提として、二段階認証プロセス が必要です。
二段階認証プロセスを導入していない人は以下から導入してください。
https://www.google.com/landing/2step/?hl=ja
"アプリ パスワード" については以下を参考に取得してどこかに保存しておいてください。
https://support.google.com/accounts/answer/185833?hl=ja
4. 依存性の追加 (gradleファイルへの記述)
次に gradle.build ファイルへ以下の記述をします。
1 |
implementation("org.springframework.boot:spring-boot-starter-mail") |
mavenを使用している方は以下を参考に依存性の追加をお願いします。
https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail/2.2.4.RELEASE
5. application.yml ファイルへの定義追加
このパートがネットで調べてなかなか出てこなかった個所になります。
正確には、出てきたのですが、その情報でプログラムを実行すると、
以下のエラーが出てきてしまいました。
1 |
could not convert socket to tls |
さて、application.yml ファイルに以下を記述してください。
1 2 3 4 5 6 7 8 9 10 11 |
spring: mail: host: smtp.gmail.com port: 587 # あなたのGMailのアドレス username: xxx@gmail.com # アプリ パスワード password: xxx properties.mail.smtp.auth: true properties.mail.smtp.starttls.enable: true properties.mail.smtp.ssl.trust: smtp.gmail.com |
application.propertiesを使用している方は、以下を参考に書き換えてください。
1 2 3 4 5 6 7 |
spring.mail.host = smtp.gmail.com spring.mail.port = 587 spring.mail.username = xxx@gmail.com spring.mail.password = xxx spring.mail.properties.mail.smtp.auth = true spring.mail.properties.mail.smtp.starttls.enable = true spring.mail.properties.mail.smtp.ssl.trust = smtp.gmail.com |
6. メール送信クラスの作成
ここは、ネットで検索できる情報とほぼ同様なので、ベーシックな実装のみ載せておきます。
詳細なユースケースに応じてGoogleで検索頂くのが良いと思います。
検索ワード例) Spring Boot mail
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import org.springframework.beans.factory.annotation.Autowired import org.springframework.mail.MailSender import org.springframework.mail.SimpleMailMessage import org.springframework.stereotype.Component /** * メールを送信するクラスです. */ @Component class MyMailSender { @Autowired lateinit var sender: MailSender fun sendMail(title: String, text: String) { val msg = SimpleMailMessage() msg.setFrom("xxx@gmail.com") msg.setTo("xxx@gmail.com") msg.setSubject(title) msg.setText(text) this.sender.send(msg) } } |
7. 終わりに
本日はSpring Boot を使用してGMailからメールを送信する方法について解説しました。
誤りなどがあればご指摘いただけますと幸いです。
また、こんなことも解説して欲しい、ということがありましたらお問い合わせからご連絡をお願い致します。