JAVA/SpringBoot
Spring boot - Thymeleaf 템플릿 메일발송
realizers
2022. 4. 28. 15:00
728x90
반응형
라이브러리 추가
implementation "org.springframework.boot:spring-boot-starter-mail"
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
application.yml 설정
spring:
mail:
host: smtp.gmail.com
port: 587
username: 구글 아이디
password: 구글 2차 비밀번호
properties:
mail:
smtp:
auth: true
starttls:
enable: true
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: HTML
encoding: UTF-8
cache: false
메일 발송을 위한 템플릿 페이지 생성
- resources > templates > mail.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<span>가입을 환영합니다. </span>
<span th:text="${name}"></span>
<span>님</span>
</body>
</html>
MailHandler 클래스 생성
@Component
@RequiredArgsConstructor
public class MailHandler {
private final JavaMailSender javaMailSender;
private final SpringTemplateEngine templateEngine;
/**
* 이메일 발송 함수
* @param title 이메일 제목
* @param to 받는 사람
* @param templateName 템플릿 이름
* @param values 이메일에 들어갈 값
* @throws MessagingException
* @throws IOException
*/
public void send(String title, String to, String templateName, HashMap<String, String> values) throws MessagingException, IOException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
// 제목 설정
helper.setSubject(title);
// 수신자 설정
helper.setTo(to);
// html페이지에 뿌릴 값 세팅
Context context = new Context();
values.forEach((key, value) -> {
context.setVariable(key, value);
});
String html = templateEngine.process(templateName, context);
helper.setText(html, true );
javaMailSender.send(message);
}
}
💡 templateEngine.process();
첫번째 인자는 templates 폴더에 있는 파일명을 가리킵니다. ex) prefix + mail + suffix
두번째 인자는 템플릿에 데이터를 바인딩 하기 위한 데이터를 key / value 구조로 세팅하여 넘겨주면 됩니다.
String html = templateEngine.process(templateName, context);
이메일 발송 코드
@RestController
@RequiredArgsConstructor
public class AuthController {
private final MailHandler mailHandler;
@PostMapping("/mail-send")
public void mailSend(String email, String name) throws MessagingException, IOException {
HashMap<String, String> emailValues = new HashMap<>();
emailValues.put("name", name);
mailHandler.send("가입을 환영합니다", email, "mail", emailValues);
}
}
실행 결과
참고 )
728x90
반응형