LoginSignup
10
5

More than 3 years have passed since last update.

【SpringBoot】メールを送信する

Last updated at Posted at 2019-07-05

spring-boot-starter-mailを使ってmailを送信します。
SpringBootは2.0.9で書いています。

依存を追加

spring-boot-starter-mailの依存を追加します。

pom.xml
    <!-- 省略 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
    <!-- 省略 -->

設定を追加

spring.mail配下に以下を設定します。
この設定ではGmail / GSuiteユーザーにのみメールを送信できます(後述)。

application.yml
spring:
  mail:
    host: aspmx.l.google.com
    port: 25

ここで設定した内容について

今回はテスト用ということで、Googleの制限付き Gmail SMTP サーバーを使ってメール送信を行なっています。
この設定では、GmailまたはGSuiteユーザーのみにメール送信が可能です。
Gmail SMTP サーバーに関する詳細はドキュメントを参照してください。

補足

SpringBootにおけるmail関連設定の詳細はドキュメントの# Emailに載っています。

テスト用の送信コードを追加

以下を追加することで起動時にメールを送ることができます。

import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;

@Component
public class MailUtil {
    private final MailSender mailSender;

    public MailUtil(MailSender mailSender) {
        this.mailSender = mailSender;

        this.sendMail();
    }

    public void sendMail() {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom("test@test.jp"); // 送信元メールアドレス
        mailMessage.setTo(/* 送信先メールアドレス */);
        mailMessage.setCc(/* ccに入れるメールアドレス */);
        mailMessage.setBcc(/* bccに入れるメールアドレス */);
        mailMessage.setSubject("テスト用表題");
        mailMessage.setText("ローカルから送る用テストメッセージ");

        try {
            mailSender.send(mailMessage);
        } catch (MailException e) {
            // TODO: エラー処理
        }
    }
}

送信結果

以下のようにメールを受け取ることができます。
スクリーンショット 2019-07-05 20.png

10
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
5