[SpringBoot] 이메일 전송 ( JavaMailSender, MimeMessageHelper )
Spring Boot | 메일 발송 기능 구현하기 (Gmail)
[SpringBoot] 메일 발송(JavaMailSender)
스프링(Spring) MailSender, JavaMailSender (메일 발송)
구글 계정 설정 (Gmail SMTP Server을 활용하기 위한 절차) ⇒ 이거 참고하기 https://velog.io/@tjddus0302/Spring-Boot-메일-발송-기능-구현하기-Gmail#:~:text=Spring Boot | 메일 발송 기능 구현하기 (Gmail),수정 ... 5 코드 작성 ... 기타 항목
springboot 의존성 추가
implementation 'org.springframework.boot:spring-boot-starter-mail'
환경 변수 설정 (application.properties와 환경 변수 설정)
Git/GitHub에 Gmail 비밀번호가 드러나지 않도록 조심 구글 계정 설정하면서 얻은 앱 비밀번호를 password로 입력해줘야 함.
What Is Gmail SMTP and How to Use Gmail With My Domain?

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=${mail.username}
spring.mail.password=${mail.password}
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.starttls.enable=true
spring:
mail:
host: smtp.gmail.com # 1
port: 587 # 2
username: ${mail.username} # 3
password: ${mail.password} # 4
properties:
mail:
smtp:
auth: true # 5
timeout: 5000 # 6
starttls:
enable: true # 7
JavaMailSender와 MimeMessageHelper을 이용해서 서비스 구현
public class MailHandler {
private JavaMailSender sender;
private MimeMessage message;
private MimeMessageHelper messageHelper;
// 생성자
public MailHandler(JavaMailSender jSender) throws MessagingException {
this.sender = jSender;
message = jSender.createMimeMessage();
messageHelper = new MimeMessageHelper(message, true, "UTF-8");
}
// 보내는 사람 이메일
public void setFrom(String fromAddress) throws MessagingException {
messageHelper.setFrom(fromAddress);
}
// 받는 사람 이메일
public void setTo(String email) throws MessagingException {
messageHelper.setTo(email);
}
// 제목
public void setSubject(String subject) throws MessagingException {
messageHelper.setSubject(subject);
}
// 메일 내용
public void setText(String text, boolean useHtml) throws MessagingException {
messageHelper.setText(text, useHtml);
}
// 첨부 파일
public void setAttach(String displayFileName, String pathToAttachment) throws MessagingException, IOException {
File file = new ClassPathResource(pathToAttachment).getFile();
FileSystemResource fsr = new FileSystemResource(file);
messageHelper.addAttachment(displayFileName, fsr);
}
// 이미지 삽입
public void setInline(String contentId, String pathToInline) throws MessagingException, IOException {
File file = new ClassPathResource(pathToInline).getFile();
FileSystemResource fsr = new FileSystemResource(file);
messageHelper.addInline(contentId, fsr);
}
// 발송
public void send() {
try {
sender.send(message);
}catch(Exception e) {
e.printStackTrace();
}
}
}
public void mailSend(MailDto mailDto) {
try {
MailHandler mailHandler = new MailHandler(mailSender);
// 받는 사람
mailHandler.setTo(mailDto.getAddress());
// 보내는 사람
mailHandler.setFrom(MailService.FROM_ADDRESS);
// 제목
mailHandler.setSubject(mailDto.getTitle());
// HTML Layout
String htmlContent = "<p>" + mailDto.getMessage() +"<p> <img src='cid:sample-img'>";
mailHandler.setText(htmlContent, true);
// 첨부 파일
mailHandler.setAttach("newTest.txt", "static/originTest.txt");
// 이미지 삽입
mailHandler.setInline("sample-img", "static/sample1.jpg");
mailHandler.send();
}
catch(Exception e){
e.printStackTrace();
}
}
엘리먼트가 많은 layout을 작성해야 한다면, 별도로 템플릿을 생성하는 MailTemplateService 서비스를 두는 것이 좋다고 생각됩니다. 즉, 컨트롤러에서 MailTemplateService 서비스를 호출하여 메시지 내용을 보여주는 DOM를 만들어내고, 해당 DOM을 MailService에 전달하면 DOM 생성과 메일발송의 역할이 각 서비스로 분할되어 관리가 깔끔해질 것 같습니다.
[ERROR] org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8 https://support.google.com/mail/?p=BadCredentials r12sm16296716pgu.93 - gsmtp
⇒ applicatioy.yml에 아이디 비밀번호를 제대로 입력했는데도 해당 에러가 발생하면서 메일이 발송되지 않으면, 여기에서 "보안 수준이 낮은 앱 허용: 사용"으로 바꿔주시면 됩니다.