LoginSignup
47
57

More than 5 years have passed since last update.

Spring-bootからメールを送信するまで

Last updated at Posted at 2016-01-20

目的

テキストだけのメールを送信する

googleの
二段階認証でどハマりしたため、メモ。

環境

IDE STS
Spring boot 1.3.1
メールの送信spring-boot-starter-mail

手順

プロジェクトの構成
スクリーンショット 2016-01-20 23.29.29.png
メール送信では、
・pom
・application.yml
・メール送信のためのjava
を編集する

pom

いくつかの方法があるが、今回はspring-boot-starter-mailを利用する
pomファイルに依存性を設定

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

メールの設定

application.ymlを編集する

application.yml
spring:
  datasource:
    driverClassName: org.h2.Driver
    url: jdbc:h2:file:/tmp/mvp_mitsumori01 #
    username: sa
    password:
  jpa:
    hibernate.ddl-auto: validate #
  thymeleaf.cache: false

  mail:
    host: smtp.gmail.com
    port: 587
    username: <googleのメールアドレス>
    password: <アプリパスワード>
    properties.mail.smtp.auth: true
    properties.mail.smtp.starttls.enable: true

datasourceは関係ない
mailの方に今回利用するgmailの設定を記載する

問題は、<アプリパスワード>ってなんだ
ということですが、googleの設定のところで後述

java

とりあえず送信の確認のため、
mainが実行されると同時にメールが送信されるようにする。

MailTest02Application.java
package com.example;

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 MailTest02Application {

    public static void main(String[] args) {
        try (ConfigurableApplicationContext ctx = SpringApplication.run(MailTest02Application.class, args)) {
            ctx.getBean(MailTest02Application.class).sendMail();
        }
    }
    @Autowired
    private MailSender sender;

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

        msg.setFrom("test@mail.com");
        msg.setTo("<メールアドレス>");
        msg.setSubject("テストメール"); //タイトルの設定
        msg.setText("Spring Boot より本文送信"); //本文の設定

        this.sender.send(msg);
    }
}

googleの設定

googleの「アカウント」から
スクリーンショット 2016-01-20 23.36.14.png

アカウントの管理のgoogleへのログインへ入り

スクリーンショット 2016-01-20 23.37.43.png
アプリパスワードを実行する
すると、
パスワードとなる対象のOSやアプリケーション(今回の場合メールを指定)を指定できるので、
当該アプリの設定で生成すると
パスワードが生成される。

これを、spring-bootからアクセス時利用する。

それが、application.ymlに設定した
<アプリパスワード>

今後これについて、次はファイル添付の方法等、出来るようになったらまとめる

参考

47
57
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
47
57