인증 메일은 메일 발송 기능과 Redis를 이용하여 구현 하였음.
Redis의 일정 시간동안 데이터가 유지되는 기능을 사용
mail기능과 redis기능 의존성 추가
implementation 'org.springframework.boot:spring-boot-starter-mail'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
spring:
redis:
host: {IP}
port: 6379
mail:
host: smtp.gmail.com
port: 587
username: {계정}@gmail.com
password: {password}
properties:
mail:
transport:
protocol: smtp
smtp:
port: 25
auth: true
starttls:
enable: true
required: true
application.yml에 위와 같은 설정을 추가해줘야 한다.
gamil 사용 시 인증을 받도록 계정 인증을 따로 받아야 한다. 이 부분에서 안되는 바람에 많이 햇갈렸다.
디테일한 설정은 기억이 잘…. 검색해보자!
public class MailUtils {
private JavaMailSender mailSender;
private MimeMessage message;
private MimeMessageHelper messageHelper;
public MailUtils(JavaMailSender mailSender) throws MessagingException {
this.mailSender = mailSender;
message = this.mailSender.createMimeMessage();
messageHelper = new MimeMessageHelper(message, true, "UTF-8");
}
// 받는 사람 eamil
public void setTo(String email) throws MessagingException{
messageHelper.setTo(email);
}
// 메일 제목
public void setSubject(String subject) throws MessagingException{
messageHelper.setSubject(subject);
}
// 메일 내용 html을 사용하면 꾸밀 수 있다.
public void setText(String htmlContent) throws MessagingException{
messageHelper.setText(htmlContent);
}
// 보내는 사람 email과 노출되는 이름을 정해줌
public void setFrom(String email, String name) throws UnsupportedEncodingException, MessagingException{
messageHelper.setFrom(email, name);
}
// 이건 뭐더라?
public void addInline(String contentId, DataSource dataSource) throws MessagingException {
messageHelper.addInline(contentId, dataSource);
}
// 보내버리기!
public void send() {
mailSender.send(message);
}
}
JavaMailSender를 이용한 메일 전송 클래스를 하나 만들어 주었다.
public ApiResponse mailSender(String email) throws MessagingException, UnsupportedEncodingException {
MailUtils mailUtils = new MailUtils(mailSender);
mailUtils.setFrom("[email protected]", "테스트");
mailUtils.setTo(email);
mailUtils.setSubject("인증코드 발송");
mailUtils.setText("테스트 코드");
mailUtils.send();
ApiResponse apiResponse = new ApiResponse(200, "발송 성공");
return apiResponse;
}