본문 바로가기
웹 개발/Back End

스프링 이메일 전송 기능

by L3m0n S0ju 2025. 4. 19.

 

 

이메일 전송하는 방법을 정리해봤습니다.

 

 

    /**
     * 이메일 인증 메일
     */
    public static final String AUTH_EMAIL_TITLE = "[" + SERVICE_NAME + "] 이메일 인증 요청";
    public static final String AUTH_EMAIL_BODY = "<html><body>" +
            "<h1>이메일 인증번호 안내</h1>" +
            "<div>어쩌구 저쩌구</div>" +
            "<div>감사합니다.</div>" +
            "</body></html>";

 

우선은 보낼 제목과 내용을 작성해줍니다.

 

 

 

 

    @Transactional
    public void sendAuthenticationEmail(String email, String authNumber) {
        EmailNotifyRequestDto emailNotifyRequestDto = EmailNotifyRequestDto.of(
                email,
                EmailConstant.AUTH_EMAIL_TITLE,
                String.format(EmailConstant.AUTH_EMAIL_BODY, authNumber)
        );

        sendWithResponse(emailNotifyRequestDto, MailType.AUTHENTICATION);
    }

 

다음으로 이메일 전송 Dto를 작성해주고 이메일 전송 함수를 실행합니다.

 

 

 

 

 

 private void sendWithResponse(EmailNotifyRequestDto emailNotifyRequestDto, MailType mailType) {
        EmailNotifyResponseDto emailNotifyResponseDto = emailNotificationService.sendWithResponse(emailNotifyRequestDto);
        try {
            if (emailNotifyResponseDto.getMailSendStatus().isFail()) {
                throw new PluginException(PluginExceptionCode.EMAIL_NOTIFICATION_FAILED);
            }
        } catch (PluginException e) {
            // 실패시, 1회 재전송
            emailNotifyResponseDto = emailNotificationService.sendWithResponse(emailNotifyRequestDto);
            
            // 로그 남기기 ... (생략)
           
        } finally {
            saveMailHistory(emailNotifyRequestDto, emailNotifyResponseDto, mailType);
        }
    }

이메일 전송 함수를 실행하고 실패하는 경우 1회를 재전송 하고 로그를 남기는 코드입니다.

 

 

 

 

    private final JavaMailSender mailSender;
    
    public <T> EmailNotifyResponseDto sendWithResponse(@NonNull T t) {
        EmailNotifyRequestDto emailNotifyRequestDto = (EmailNotifyRequestDto) t;

        try {
            MimeMessagePreparator messagePreparator = mimeMessage -> {
                MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
                messageHelper.setFrom("sender@example.com");
                messageHelper.setTo("receiver@example.com");
                messageHelper.setSubject(emailNotifyRequestDto.getSubject()); // 제목
                messageHelper.setText(emailNotifyRequestDto.getContents(), true); // 내용
            };

            mailSender.send(messagePreparator);
        } catch (MailException me) {
            // 로그 남기기... (생략)
            return EmailNotifyResponseDto.of(MailSendStatus.FAIL, me.getMessage());
        } catch (Exception e) {
            // 로그 남기기... (생략)
            return EmailNotifyResponseDto.of(MailSendStatus.FAIL, e.getMessage());
        }
        return EmailNotifyResponseDto.of(MailSendStatus.SUCCESS, "");
    }

MimeMessagePreparator를 import해서 위 코드처럼 송신자, 수신자, 메일 제목, 메일 내용을 넣어주고 mailSender를 통해 메일을 전송하면 됩니다. SMTP 설정은 구글이나 네이버 SMTP를 사용하셔도 되고 회사 자체 메일 서버가 있으면 사용하면 됩니다.

 

 

 

@Getter
public class EmailNotifyResponseDto {

    private final MailSendStatus mailSendStatus;
    private final String resultMessage;

    @Builder(access = AccessLevel.PRIVATE)
    private EmailNotifyResponseDto(MailSendStatus mailSendStatus, String resultMessage) {
        this.mailSendStatus = mailSendStatus;
        this.resultMessage = resultMessage;
    }

    public static EmailNotifyResponseDto of(@NonNull MailSendStatus mailSendStatus, @NonNull String resultMessage) {
        return EmailNotifyResponseDto.builder()
                .mailSendStatus(mailSendStatus)
                .resultMessage(resultMessage)
                .build();
    }
}

메일 성공 여부 응답 DTO는 위 코드와 같이 상태값과 메시지를 받는식으로 원하는대로 작성하면 됩니다.

'웹 개발 > Back End' 카테고리의 다른 글

백엔드 다국어 처리  (0) 2025.05.31
RabbitMQ 개념  (0) 2025.04.20
스프링 배치(Spring Batch)란?  (0) 2025.04.12
이벤트 리스너 사용법  (0) 2024.09.17
Java 헷갈리는 것들 모음  (0) 2024.09.16

댓글