[JAVA] Spring Boot에서 이메일 발송 기능 구현하기 (JavaMailSender)

이메일 발송 기능은 사용자 인증, 알림, 문의 응답 등 다양한 웹 서비스에서 필수로 사용됩니다.
Spring Boot에서는 JavaMailSender를 통해 SMTP 서버와 연동하여 간단히 구현할 수 있습니다.
Gmail SMTP를 예시로 간단한 텍스트 메일부터 HTML 템플릿 메일 발송까지 전체 과정을 정리해보겠습니다.

 

 


의존성 추가 (Gradle 기준)

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-mail'
}

빌드 후 자동으로 JavaMailSender Bean이 등록됩니다.

 

 

SMTP 설정 (Gmail 기준)

# application.yml
spring:
  mail:
    host: smtp.gmail.com
    port: 587
    username: your_email@gmail.com
    password: your_app_password
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true

Gmail은 2단계 인증 + 앱 비밀번호를 사용해야 합니다.
구글 계정 > 보안 > 앱 비밀번호에서 생성하세요.

 

 

이메일 서비스 클래스 작성

@Service
public class MailService {

    private final JavaMailSender mailSender;

    public MailService(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void sendSimpleMail(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        message.setFrom("your_email@gmail.com"); // 생략 시 설정의 username 사용
        mailSender.send(message);
    }

    public void sendHtmlMail(String to, String subject, String htmlContent) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, false, "UTF-8");

        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlContent, true);
        helper.setFrom("your_email@gmail.com");

        mailSender.send(message);
    }
}

 

 

Controller에서 호출 예시

@RestController
@RequestMapping("/api/mail")
public class MailController {

    private final MailService mailService;

    public MailController(MailService mailService) {
        this.mailService = mailService;
    }

    @PostMapping("/send")
    public ResponseEntity<String> sendMail(@RequestParam String to, @RequestParam String subject, @RequestParam String content) {
        mailService.sendSimpleMail(to, subject, content);
        return ResponseEntity.ok("메일 발송 완료");
    }
}

 

 

HTML 템플릿 적용 (선택)

복잡한 이메일 디자인은 Thymeleaf 템플릿 엔진을 활용해 렌더링 후 HTML을 발송하는 것이 좋습니다.

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
// 템플릿 적용 메일 예시
public String renderTemplate(String name) {
    Context context = new Context();
    context.setVariable("name", name);
    return templateEngine.process("welcome-email", context); // resources/templates/welcome-email.html
}

 

 

예외 처리 및 실전 고려사항

  • 발송 실패 시 MailException, MessagingException 처리 필요
  • 외부 서비스이므로 비동기 처리 또는 큐 기반 처리 권장 (예: Kafka)
  • 메일 전송 로그 및 성공 여부 기록 필요 (DB 등)
  • HTML 메일은 스팸 필터 우회를 위한 기본 포맷 구성 필요

 


 

Spring Boot에서는 JavaMailSender를 활용해 이메일 기능을 빠르게 도입할 수 있습니다.
간단한 인증 메일부터 HTML 기반 마케팅 메일까지 다양한 형태로 확장 가능하며, 실무에서는 반드시 템플릿, 로깅, 예외처리를 포함한 구조로 설계해야 유지보수성이 확보됩니다.