이번에는 타임리프 템플릿을 이용해서
메일로 코드를 발송하는 로직을 만들어보았다 +_+
application.yml
mail:
host: smtp.naver.com #smtp 서버 주소
port: 465 # 메일 인증서버 포트
username: #네이버 아이디
password: #네이버 비밀번호
properties:
mail:
smtp:
starttls:
enable: true
# required: true
auth: true
# connectiontimeout: 5000
# timeout: 5000
# writetimeout: 5000
ssl:
#trust: smtp.naver.com
enable: true #반드시 필요 -> SSL 필요로 되어있으면
MailService 는 !?
@Service
@PropertySource("classpath:application.yml")
public class MailServiceImpl implements MailService{
private final JavaMailSender mailSender;
private final SpringTemplateEngine templateEngine; //타임리프를 사용하기 위한 객체
@Value("${mail.id}")
private String fromEmail;
private MimeMessage message;
private String title;
private String randomCode;
private final String charset = "UTF-8";
private final String html = "html";
public MailServiceImpl(JavaMailSender mailSender, SpringTemplateEngine templateEngine) {
this.mailSender = mailSender;
this.templateEngine = templateEngine;
}
@Override
public String joinCodeSend(String toEmail) {
createCode();
title = "오늘도 휴일 * 가입 코드";
try {
message = mailSender.createMimeMessage();
message.addRecipients(RecipientType.TO, toEmail);
message.setSubject(title);
message.setFrom(fromEmail);
message.setText(contextJoin(randomCode), charset, html);
mailSender.send(message);
} catch (MessagingException e) {
return "전송 오류";
}
return randomCode;
}
@Override
public String contextJoin(String code) {
Context context = setContext("code", code);
return templateEngine.process("email/joinMailForm", context);
}
public void createCode() {
int min = 1000;
int max = 9999;
StringBuffer buffer = new StringBuffer();
Random random = new Random();
int code = random.nextInt(max-min)+min;
randomCode = buffer.append(code).toString();
}
private Context setContext(String key, String value) {
Context context = new Context();
context.setVariable(key, value);
return context;
}
}
@Service
@PropertySource("classpath:application.yml")
public class MailServiceImpl implements MailService {
private final JavaMailSender mailSender;
private final SpringTemplateEngine templateEngine; //타임리프를 사용하기 위한 객체
@Value("${mail.id}")
private String fromEmail;
private MimeMessage message;
private String title;
private String randomCode;
private final String charset = "UTF-8";
private final String html = "html";
기본으로 필요한 JavaMailSender 와 MimeMessage ,
타임리프 템플릿을 이용할 SpringTemplateEngine 을 선언하고
fromEmail(보내는이메일) 을 공개하지 않기 위해
@Value 를 사용해 application.yml 안으로 숨겼다 !
public void createCode() {
int min = 1000;
int max = 9999;
StringBuffer buffer = new StringBuffer();
Random random = new Random();
int code = random.nextInt(max-min)+min;
randomCode = buffer.append(code).toString();
}
일단 createCode 로 랜덤 4자리 숫자 코드를 만들어준다 :)
@Override
public String contextJoin(String code) {
Context context = setContext("code", code);
return templateEngine.process("email/joinMailForm", context);
}
private Context setContext(String key, String value) {
Context context = new Context();
context.setVariable(key, value);
return context;
}
이건 타임리프 템플릿을 사용하기 위한 코드인데
setContext 에서 setVariable 로 템플릿에 파라미터 값을 보내주고
context 를 반환해준다
그리고 .process("템플릿경로", context) 을 설정하고 반환해준다
@Override
public String joinCodeSend(String toEmail) {
createCode();
title = "오늘도 휴일 * 가입 코드";
try {
message = mailSender.createMimeMessage();
message.addRecipients(RecipientType.TO, toEmail);
message.setSubject(title);
message.setFrom(fromEmail);
message.setText(contextJoin(randomCode), charset, html);
mailSender.send(message);
} catch (MessagingException e) {
return "전송 오류";
}
return randomCode;
}
마지막으로
보내는 이메일 / 제목 / 받는 이메일 / context, 캐릭터셋(utf-8), 템플릿타입(html) 을 설정해주고
해당 메세지를 메일로 보내면 완성 :)
randomCode 를 반환해서 컨트롤러에서 받아 저장하는 것은 필수 !
@Controller
@RequestMapping("/join")
public class MemberJoinController {
private String randomCode;
private final MailService mailService;
@ResponseBody
@PostMapping("/emailSend")
public String emailCodeSend(@RequestBody DoubleCheckDto doubleCheckDto) {
if (stringNullCheck(
doubleCheckDto.getEmail())) {
return "확인 불가";
}
randomCode = mailService.joinCodeSend(doubleCheckDto.getEmail());
return randomCode;
}
@ResponseBody
@PostMapping("/codeCheck")
public String codeCheck(@RequestBody DoubleCheckDto doubleCheckDto) {
String code = doubleCheckDto.getCode();
if (stringNullCheck(code)) {
return "확인 불가";
}
if (code.equals(randomCode)) {
return "코드 일치";
}
return "코드 불일치";
}
}
컨트롤러에서
코드를 발송하는 메서드와 검증하는 메서드를 추가한다 ^0^///
메일 템플릿은?
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<div class="space-medium">
<div class="container">
<div class="row">
<div class="table-center">
<p>안녕하세요 오늘도 휴일입니다!<br>
아래의 가입 코드를 입력해주세요</p>
<h1 class="fan-only-h1 mail-code">가입 코드<br>
<h1 th:text="${code}"></h1></h1>
</div>
</div>
</div>
</div>
</body>
</html>
이런 식으로 넣어주었다
th:text="${code}" 로 파라미터를 받아준다^0^
그렇다면 결과는 ?
포스트맨으로 테스트해보자 !
json 으로 이메일을 보내주면,
아래에 랜덤 코드를 반환하게 했다^0^/
메일은 무사히 왔음 !
코드를 입력하면 코드 일치까지 무사히 반환 ^ㅅ^ /
기분 좋게 성공!
'혼자서 개발새발' 카테고리의 다른 글
Pageable 로 게시판 페이징을 해야 하는데 특정 컬럼이 존재한다면 안 보여주고 싶다 (0) | 2023.05.05 |
---|---|
Spring Security ) JWT 토큰 로그인 구현을 해보았다 (0) | 2023.03.25 |
Spring Security ) SNS 로그인 구현(내가 보려고 정리...) (1) | 2023.01.09 |
페이징 할 때 Entity로 받고, Dto로 변환하자! (1) | 2023.01.05 |
JPA ) QueryDsl , Pageble 을 이용해 페이징을 하다! (0) | 2023.01.04 |