Memo

メモ > 技術 > フレームワーク: SpringBoot > メール送信

■メール送信
Spring Boot Starter Mailを導入することで対応できる メールを送信するためのSMTP情報は、あらかじめ用意しておく pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
application.properties (ロリポップの場合)
spring.mail.host=smtp.lolipop.jp spring.mail.port=587 spring.mail.username=ロリポップのメールアドレス spring.mail.password=ロリポップのメールパスワード spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true
application.properties (Gmailの場合)
spring.mail.host=smtp.gmail.com spring.mail.port=587 spring.mail.username=Gmailのメールアドレス spring.mail.password=Gmailのアプリパスワード spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true
src/main/java/com/example/demo/controller/HomeController.java
package com.example.demo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.MailException; import org.springframework.mail.MailSender; import org.springframework.mail.SimpleMailMessage; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import java.time.LocalDateTime; @Controller public class HomeController { @Autowired private final MailSender mailSender; public HomeController(MailSender mailSender) { this.mailSender = mailSender; } @GetMapping(value = "/") String index() { return "home/index"; } @GetMapping(value = "/now") String now(Model model) { model.addAttribute("time", LocalDateTime.now()); return "home/now"; } @GetMapping(value = "/mail") String mail() { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom("from@example.com"); message.setTo("to@example.com"); message.setSubject("SpringBootからのメール送信"); message.setText("テスト。\r\nこれはSpringBootからのメール送信です。"); try { mailSender.send(message); } catch (MailException e) { e.printStackTrace(); } return "home/mail"; } }
templates/home/mail.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout/frontend}"> <head> <title>メール | Demo</title> </head> <body> <th:block layout:fragment="content"> <main> <p>メールを送信しました。</p> </main> </th:block> </body> </html>
これで http://localhost:8080/mail にアクセスするとメールが送信される SpringBoot メール送信のサンプル | ITSakura https://itsakura.com/sb-mailsend 【Spring Boot】メール送信 https://b1san-blog.com/post/spring/spring-mail/

Advertisement