개요

이메일 인증은 어떻게 구현하면 좋을까?
회원가입 요청이 들어왔을 때 request에 적힌 사용자 이메일로 인증 코드를 보내면 될 것 같다.
그리고 사용자가 인증 코드를 서버로 보내면, 우리가 보내 준 코드와 일치 하는지 검토 하자.
일치 시 회원 가입 처리를 하면 되지 않을까?

 

저보다는 더 복잡하겠지만 일단 중요한 건, Spring 서버에서 어떻게 이메일을 보낼 수 있을까이다.

 

 

SMTP

SMTP는 Simple Mail Transfer Protocol의 약자이다.
인터넷을 통해 이메일 메시지를 전송하는 데 사용되는 통신 프로토콜이다.

 

google SMTP

Gmail로도 SMTP를 사용할 수 있을까? 당연하다!

 

App passwords 등록

우리가 만든 어플리케이션에서 구글 계정에 접근하기 위해 패스워드를 등록해야 한다.

만약 App passwords라는 설정을 검색해도 보이지 않는다면 2단계 인증을 하지 않은 것이다.

 

Java Mail Sender

SMTP를 사용하기 위해서는 Java Mail Sender 디펜던시를 추가할 필요가 있다.

implementation 'org.springframework.boot:spring-boot-starter-mail'

 

JavaMailSender는 스프링 프레임워크의 인터페이스이다.

 

Docs

 

JavaMailSender (Spring Framework 6.1.8 API)

Extended MailSender interface for JavaMail, supporting MIME messages both as direct arguments and through preparation callbacks. Typically used in conjunction with the MimeMessageHelper class for convenient creation of JavaMail MimeMessages, including atta

docs.spring.io

 

이 인터페이스를 구현한 JavaMailSenderImpl 클래스를 간편하게 사용할 수 있다.

 

JavaMailSenderImpl (Spring Framework 6.1.8 API)

Obtain and connect a Transport from the underlying JavaMail Session, passing in the specified host, port, username, and password.

docs.spring.io

 

docs에서 우리가 설정 해줄 수 있는 것이 무엇인지 확인하고 필요에 따라 쓰도록 하자.

 

SetJavaMailProperties에서는 세션에 대한 프로퍼티를 추가해 줄 수 있다.

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.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000

 

    @Bean
    public JavaMailSender javaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

        mailSender.setHost(host);
        mailSender.setPort(port);
        mailSender.setUsername(username);
        mailSender.setPassword(password);
        mailSender.setDefaultEncoding("UTF-8");
        mailSender.setJavaMailProperties(getMailProperties());

        return mailSender;
    }

    private Properties getMailProperties() {
        Properties properties = new Properties();

        properties.put("mail.smtp.auth", auth);
        properties.put("mail.smtp.starttls.enable", starttlsEnable);
        properties.put("mail.smtp.starttls.required", starttlsRequired);
        properties.put("mail.smtp.connectiontimeout", connectionTimeout);
        properties.put("mail.smtp.timeout", timeout);
        properties.put("mail.smtp.writetimeout", writeTimeout);

        return properties;
    }

 

우리 팀에서는 SmtpConfig라는 config 클래스를 만들어서 JavaMailSenderImpl을 생성하고 Bean에 등록해 사용하는 방식을 채택하였다.

각자의 프로젝트 상황에 맞춰 하도록 하자.

 

    public void sendEmail(String toEmail, String title, String content) {
        SimpleMailMessage message = createEmailForm(toEmail, title, content);

        try {
            mailSender.send(message);
        } catch (Exception e) {
            log.error("MailService.sendEmail exception occur toEmail: {}, " +
                    "title: {}, content: {}", toEmail, title, content);
            throw new RuntimeException("이메일 전송 실패");
        }
    }

    private SimpleMailMessage createEmailForm(String toEmail, String title, String content) {
        SimpleMailMessage message = new SimpleMailMessage();

        message.setTo(toEmail);
        message.setSubject(title);
        message.setText(content);

        return message;
    }

 

SmtpService에서 메시지를 보내는 부분이다.

위 JavaMailSender Docs에서 볼 수 있듯 이메일을 보낼 때는 send라는 메서드를 사용한다.

또한 파라미터로는 SimpleMailMessage 가변인자 들어간다.

즉 메일 여러 개를 한 번에 보낼 수 있다.

 

Docs

 

SimpleMailMessage (Spring Framework 6.1.8 API)

Models a simple mail message, including data such as the from, to, cc, subject, and text fields. Consider JavaMailSender and JavaMail MimeMessages for creating more sophisticated messages, for example messages with attachments, special character encodings,

docs.spring.io

 

여기서는 사용자 이메일 주소, 제목, 내용만 설정해 주고 있다.

 

 

여기까지 Spring에서 Gmail을 보내는 방법에 대해 알아보았다.

+ Recent posts