Spring Boot 에서 email 보내기

알파로그·2023년 5월 23일
0

✏️ 절차

  • Google 에서 앱 비밀번호 설정 → Google 메일 설정

✏️ Google 환경설정

📍 앱 비밀번호 설정하기

  • google → 계정관리 → 보안 → 2단계 인증 → 앱 비밀번호 설정
    • 앱 선택 : 메일
    • 기기선택 : 비밀번호
    • 16자리 기기용 앱 비밀번호를 저장해준다.

📍 GMail 환경 설정

  • Gmail → 우측상단 톱니바퀴 → 모든 설정 보기 → 전달 및 POP/MAP
    • POP 다운로드 : 모든 메일에 POP 사용하기
    • IMAP 엑세스 : IMAP 사용
    • 나머지는 기본값으로 변경사항 저장

✏️ Spring Boot 환경설정

📍 Dependencies

  • 아래 두개는 타임리프를 사용할 때만 추가하면 된다.
// SMPT
implementation 'org.springframework.boot:spring-boot-starter-mail' // mail
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' // 타임 리프 사용하는 경우만 추가
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect' // 타임 리프 사용하는 경우만 추가

📍 application yml

  • username
    • aaa@gmail.com 일 경우 aaa 를 적으면 됨
  • password
    • 처음에 발급받은 앱 비밀번호
spring:
  mail:
    host: smtp.gmail.com
    port: 587
    username: 유저네임
    password: 비밀번호
    properties:
      mail:
        smtp:
          auth: true
          timeout: 5000
          starttls:
            enable: true

📍 Security 설정

  • 인증을 완료해도 POST 요청을 보낼경우 403 에러가 발생할 수 있다.
    • 이 문제를 방지하기 위해 http 객체에 설정을 추가해준다.
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http

            ...

            .csrf().disable() // csrf 비활성화
            .build();
}

✏️ Mail 기능 구현

📍 DTO 생성

import lombok.Data;

@Data
public class MailDto {

    private String address;  // 받는사람
    private String subject;  // 제목
    private String text;     // 내용
}

📍 Servcie 계층

  • FROM_ADDRESS
    • 보내는 사람의 email 주소를 입력하면 된다.
  • SimpleMailMessage
    • dto 에서 받아온 내용을 꺼내서 set 해준다.
import lombok.AllArgsConstructor;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class EmailService {

    private JavaMailSender sender;
    private static final String FROM_ADDRESS = "aaa@gmail.com";

    public void mailSend(MailDto dto) {
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setTo(dto.getAddress());
        msg.setSubject(dto.getSubject());
        msg.setText(dto.getText());
        sender.send(msg);
    }
}

📍 Controller 계층

  • Service 의 method 를 호출하고,
    endpoint 에 요청을 보내면 완료
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequiredArgsConstructor
public class EmailTestController {

    private final EmailService service;

    @PostMapping("/mail")
    public String execMail(@RequestBody @Valid MailDto dto) {
        log.info("요청확인");

        service.mailSend(dto);

        log.info("전송완료");
        return "good";
    }
}
profile
잘못된 내용 PR 환영

0개의 댓글