안녕하세요 오늘은 spring boot로 이메일을 전달하는 로직을 구현해 보겠습니다
😎 bulid.gradle
implementation 'org.springframework.boot:spring-boot-starter-mail'
build.gradle dependencies에 위 내용을 추가합니다
😎 yml 파일
mail:
host: smtp.gmail.com
port: 587
username: //계정이름
password: //계정비밀번호
properties:
mail:
smtp:
auth: true
starttls:
enalble: true
required: true
😎 service
import com.example.api.controller.dto.EmailMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.spring5.SpringTemplateEngine;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.thymeleaf.context.Context;
@Slf4j
@Service
@RequiredArgsConstructor
public class EmailService {
private final JavaMailSender javaMailSender;
private final SpringTemplateEngine templateEngine;
public void sendMail(EmailMessage emailMessage, String type) {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, "UTF-8");
mimeMessageHelper.setTo(emailMessage.getTo()); // 메일 수신자
mimeMessageHelper.setSubject(emailMessage.getSubject()); // 메일 제목
mimeMessageHelper.setText(setContext(), true); // 메일 본문 내용, HTML 여부
javaMailSender.send(mimeMessage);
log.info("Success");
} catch (MessagingException e) {
log.info("fail");
throw new RuntimeException(e);
}
}
public String setContext() {
Context context = new Context(); //context는 해당 템플릿에 값을 전달할때 사용하는 클래스입니다
return templateEngine.process("mail", context); //mail.html 템플릿을 stirng값으로 반환합니다
}
}
😎 controller
import com.example.api.controller.dto.EmailMessage;
import com.example.api.controller.dto.EmailPostDto;
import com.example.api.controller.dto.EmailResponseDto;
import com.example.api.service.EmailService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
@RequiredArgsConstructor
public class MailController {
private final EmailService emailService;
@PostMapping("/check/email")
public ResponseEntity sendJoinMail(EmailPostDto emailPostDto) {
EmailMessage emailMessage = EmailMessage.builder()
.to(emailPostDto.getEmail())
.subject("안녕하세요 테스트 문자 입니다")
.build();
emailService.sendMail(emailMessage, "email");
EmailResponseDto emailResponseDto = new EmailResponseDto();
emailResponseDto.setCode("200");
return ResponseEntity.ok(emailResponseDto);
}
}
위와 같이 로직을 구현했더니 제 메일에 템플릿 그대로 메일이 오는것을 확인할수 있었습니다 감사합니다