개발 공부 기록

[SpringBoot] 이메일 발송 기능 구현하여 이메일 인증 코드 발송하기 본문

Spring/Development Log

[SpringBoot] 이메일 발송 기능 구현하여 이메일 인증 코드 발송하기

나만없서고냥이 2023. 12. 5. 23:05

Gmail을 이용하여 회원가입 시 사용자가 입력한 이메일로 이메일 인증 코드를 발송하는 기능을 구현해보겠습니다.

✔️ 발신 이메일 계정 설정하기

Google 계정 관리에 들어가 보안 탭을 누른 후 2단계 인증을 클릭합니다.

 

2단계 인증을 설정하지 않았다면 설정해줍니다.

 

아래로 스크롤하여 앱 비밀번호를 설정해줍니다.

 

앱 이름만 입력한다면 자동으로 생성된 것을 확인할 수 있습니다.

 

Gmail로 이동한 후, 우측 상단의 톱니바퀴를 클릭하여 모든 설정 보기를 클릭합니다.

 

전달 및 POP/IMAP으로 들어가 "모든 메일에 POP 사용하기" "IMAP 사용"을 체크해줍니다.

 


✔️ SpringBoot 설정하기

1. build.gradle에 dependency 추가

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

 

2. application.yml 설정

spring:
  mail:
    host: smtp.gmail.com
    port: 587
    username: ${mail.username}
    password: ${mail.password}
    properties:
      mail:
        smtp:
          auth: true
          timeout: 5000
          starttls:
            enable: true

username에는 발신자 이메일이 jieun@gmail.com이라면 jieun이라고 작성해주시고, password에는 위에서 생성한 앱 비밀번호를 입력해주세요. 단, username이나 password와 관련된 정보는 Github에 올리지 않도록 유의해주세요.

 

저의 경우, 메일 정보 유출을 대비하여 ${mail.username}과 ${maill.password} 환경변수를 설정해주었습니다.

Run > Edit Configurations에 들어가 Modify options를 클릭합니다.

 

Environment variables에 들어가

 

다음과 같이 환경변수를 설정해줍니다.

 


✔️ 코드 작성하기

1. EmailService.java

@Service
@Transactional
@RequiredArgsConstructor
public class EmailService {
    private final JavaMailSender emailSender;
    private String certificationCode;

    public String sendCertificationCode(String toEmail) {
        MimeMessage certificationMessage = createCertificationEmail(toEmail);
        emailSender.send(certificationMessage);

        return certificationCode;
    }

    private MimeMessage createCertificationEmail(String email) {
        try {
            MimeMessage message = emailSender.createMimeMessage();
            certificationCode = createCertificationCode();

            String title = "[Bobjeong] 이메일 인증 번호 안내";
            String text =
                    "<div style='margin:20px;'>\n" +
                            "<h1> 인증 번호 확인 후 이메일 인증을 완료해주세요.</h1>" +
                            "<h1>" + certificationCode + "</h1>" +
                            "</div>";

            message.addRecipients(RecipientType.TO, email);
            message.setSubject(title);
            message.setText(text, "utf-8", "html");

            return message;
        } catch (MessagingException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    private String createCertificationCode() {
        int codeLength = 12;
        StringBuilder codeBuilder = new StringBuilder();

        Random random = new Random();
        String characters = "abcdefghijklmnopqrstuvwxyz0123456789";

        for (int i = 0; i < codeLength; i++) {
            int randomIndex = random.nextInt(characters.length());
            codeBuilder.append(characters.charAt(randomIndex));
        }

        return codeBuilder.toString();
    }
}

 

2. EmailController.java

@RestController
@RequiredArgsConstructor
public class EmailController {
    private final EmailService emailService;

    @GetMapping("/email-certification/{email}")
    public ResponseEntity<BaseResponse<String>> sendCertificationCode(@PathVariable("email") String toEmail) {
        String code = emailService.sendCertificationCode(toEmail);

        return ResponseEntity.ok().body(BaseResponse.createSuccess(code, CustomResponseStatus.SUCCESS));
    }
}

 


✔️ 테스트

쨘쨘

html 코드를 잘 작성해서 더 예쁘게 나오도록 하면 좋을 거 같습니다.😆