SpringBootからメールを送信するサンプルコード

2023/10/02に公開

build.gradleに以下を追加

// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail
implementation 'org.springframework.boot:spring-boot-starter-mail'

application.propertiesに以下を追加

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=xxx@gmail.com
spring.mail.password=Googleのアプリパスワード
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("mail")
public class MailController {

	@Autowired
	MailSender mailSender;

	@GetMapping
	public String register() {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setTo("xxx@gmail.com");
		message.setFrom("xxx@gmail.com");
		message.setSubject("てすと件名");
		message.setText("てすと本文。");

		// メール送信を実施する。
		mailSender.send(message);
		return "mail";
	}
}

mail.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>メール送信</title>
</head>
<body>
<p>メール送信</p>
</body>
</html>

参考記事
https://stackoverflow.com/questions/26594097/javamail-exception-javax-mail-authenticationfailedexception-534-5-7-9-applicatio




https://zenn.dev/codek2/books/d95901da7e8cd1

https://zenn.dev/codek2/articles/1bdbccfaf9b075

Discussion