Spring + Redis를 이용한 Email 인증 구현

2025. 8. 19. 20:08·spring & java

Google SMTP는 구글에서 무료로 메일을 발송할 수 있도록 제공해주는 서버이다.

이메일 인증 코드를 전송해주는 API를 위해 Google SMTP를 이용할 것이다. 

 

SMTP란?

단순 메일 전송 프로토콜을 의미하며, 인터넷에서 이메일을 보내기 위한 표준 통신 규약이다. 

 

 

2단계 인증 후 앱 비밀번호를 설정한다.

 

1. application.properties 설정

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=
spring.mail.password=
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.debug=true
spring.mail.properties.mail.smtp.connectiontimeout=5000 //5초

 

password에는 방금 생성한 앱 비밀번호를 넣어주면 된다.

16자리 비밀번호를 공백 없이 입력해준다.

 

 

2. MailConfig 설정

build.gradle에 먼저 spring-boot-starter-mail을 implementation 시켜줘야 한다.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;

@Configuration
public class MailConfig {

    private static final String MAIL_SMTP_AUTH = "mail.smtp.auth";
    private static final String MAIL_DEBUG = "mail.smtp.debug";
    private static final String MAIL_CONNECTION_TIMEOUT = "mail.smtp.connectiontimeout";
    private static final String MAIL_SMTP_STARTTLS_ENABLE = "mail.smtp.starttls.enable";

    // SMTP 서버
    @Value("${spring.mail.host}")
    private String host;

    // 계정
    @Value("${spring.mail.username}")
    private String username;

    // 비밀번호
    @Value("${spring.mail.password}")
    private String password;

    // 포트번호
    @Value("${spring.mail.port}")
    private int port;

    @Value("${spring.mail.properties.mail.smtp.auth}")
    private boolean auth;

    @Value("${spring.mail.properties.mail.debug}")
    private boolean debug;

    @Value("${spring.mail.properties.mail.smtp.connectiontimeout}")
    private int connectionTimeout;

    @Value("${spring.mail.properties.mail.smtp.starttls.enable}")
    private boolean startTlsEnable;

    @Bean
    public JavaMailSender javaMailService() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(host);
        javaMailSender.setUsername(username);
        javaMailSender.setPassword(password);
        javaMailSender.setPort(port);

        Properties properties = javaMailSender.getJavaMailProperties();
        properties.put(MAIL_SMTP_AUTH, auth);
        properties.put(MAIL_DEBUG, debug);
        properties.put(MAIL_CONNECTION_TIMEOUT, connectionTimeout);
        properties.put(MAIL_SMTP_STARTTLS_ENABLE, startTlsEnable);

        javaMailSender.setJavaMailProperties(properties);
        javaMailSender.setDefaultEncoding("UTF-8");

        return javaMailSender;
    }
}

 

JavaMailSender는 Spring Framework에서 제공하는 이메일 발송을 위한 인터페이스로,

자바의 기본 메일 API를 추상화하여 더욱 쉽게 사용할 수 있도록 해준다. 

 

트랜잭션을 지원하며, 테스트에 용이하다. 

 

 

3. MailService

// 인증번호 생성
    private String createCode() {
        int code = (int)(Math.random() * 900000) + 100000;
        return String.valueOf(code);
    }

 

인증번호는 Math.random() 메서드를 이용한 6자리 랜덤 숫자로 생성하였다.

 

 public void sendAuthNum(String email) throws MessagingException {
        String random = createCode(); // 인증번호 생성

        String htmlContent = "<html>" +
                "<body>" +
                "<h1 style='color: orange;'>인증번호 발송</h1>" +
                "<p>인증번호는 <b>" + random + "</b> 입니다.</p>" +
                "<p>인증번호는 5분간 유효합니다."+
                "</body>" +
                "</html>";

        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

        helper.setTo(email); //수신자 설정
        helper.setSubject("인증번호"); //메일 제목
        helper.setText(htmlContent, true); //본문 설정

        javaMailSender.send(message);
    }
}

 

 

간단한 HTML을 사용하여 인증번호를 포함한 이메일 본문을 만들었다.

JavaMailSender의 createMimeMessage() 메서드를 사용하였다. 

 

 

4. MailController

import com.example.shopping_mall.dto.response.ApiResponse;
import com.example.shopping_mall.dto.response.ApiStatus;
import com.example.shopping_mall.service.MailService;
import jakarta.mail.MessagingException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

    private MailService mailService;

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

    @PostMapping("/send")
    public ResponseEntity<ApiResponse<Void>> sendMail(@RequestBody String email) throws MessagingException {
        mailService.sendAuthNum(email);
        return ResponseEntity
                .status(ApiStatus.OK.getCode())
                .body(ApiResponse.res(ApiStatus.OK.getCode(), "인증번호가 " + email + " 로 발송되었습니다."));
    }
}

 

MimeMessageHelper.setTo()에 들어가는 값은 순수 이메일 문자열이어야 한다.

json 구조체 그대로 넣으면 오류가 발생한다. 

 

 

5. API test

 

인증 메일이 전송된것을 확인할 수 있다. 

 

다음 글에서는 Redis로 인증코드 만료 로직을 처리하는 코드를 추가 하려고 한다.

 

'spring & java' 카테고리의 다른 글

Security + OAuth 를 활용한 카카오 로그인 처리  (4) 2025.08.14
스프링 시큐티리 + JWT 를 이용한 로그인 처리  (2) 2025.08.03
Spring Event를 이용한 비동기 이벤트 처리  (0) 2025.02.23
쿠키 & 세션 / JWT  (1) 2024.08.22
JPA 영속성 컨텍스트 / 영속성 전이  (0) 2024.08.13
'spring & java' 카테고리의 다른 글
  • Security + OAuth 를 활용한 카카오 로그인 처리
  • 스프링 시큐티리 + JWT 를 이용한 로그인 처리
  • Spring Event를 이용한 비동기 이벤트 처리
  • 쿠키 & 세션 / JWT
zioni
zioni
  • zioni
    jiwon's dev.log
    zioni
  • 전체
    오늘
    어제
    • 분류 전체보기 (76)
      • spring & java (13)
      • Algorithm (14)
      • PS (37)
      • project (3)
      • experience (1)
      • etc (6)
      • study (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • Github
  • 공지사항

  • 인기 글

  • 태그

    백준2525
    자바
    백준
    java
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.6
zioni
Spring + Redis를 이용한 Email 인증 구현
상단으로

티스토리툴바