
Google 계정 > 보안 > Google에 로그인하는 방법 > 2단계 인증

앱 비밀번호

⚠️ 만들기 후 비밀번호는 다시 보여주지 않음
mail:
host: smtp.gmail.com
port: 587
username: 이메일@gmail.com
password: **** **** **** ****
properties:
mail:
smtp:
auth: true
starttls:
enable: true
의존성 추가
implementation 'org.springframework.boot:spring-boot-starter-mail'
@Slf4j
@Service
@RequiredArgsConstructor
public class MailService {
private final JavaMailSender javaMailSender;
public void sendMail(String email, EmailReqDto emailReqDto) {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
List<String> recipients = emailReqDto.getRecipient();
for (String recipient : recipients) {
try {
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, "UTF-8");
mimeMessageHelper.setTo(recipient); // 메일 수신자
String subject = email + "님께서 발송 : " + emailReqDto.getTitle();
mimeMessageHelper.setSubject(subject); // 메일 제목
mimeMessageHelper.setText(emailReqDto.getContent()); // 메일 본문 내용, HTML 여부
javaMailSender.send(mimeMessage);
System.out.println("이메일 전송");
} catch (Exception | Error e) {
throw new BobIssueException(ResponseCode.FAILED_SEND_EMAIL);
}
}
}
}
@PostMapping("/mail")
public ResponseDto sendEmail(@RequestBody EmailReqDto emailReqDto) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String email = authentication.getName(); //accessToken으로 로그인한 유저의 이메일을 구함
try{
mailService.sendMail(email, emailReqDto);
}catch (Error | Exception e) {
throw new BobIssueException(ResponseCode.FAILED_SEND_EMAIL);
}
return new ResponseDto(HttpStatus.OK, ResponseCode.SUCCESS_SEND_EMAIL, null);
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class EmailReqDto {
private String title;
private String content;
private List<String> recipient; //수신인 목록
}
여러 메일을 보내보면 구글 메일에선 정상 수신을 하지 않는 것을 볼 수 있음
이는 smtp를 구글이 스팸처리해서 발생하는 문제
👇 해결방법은 아래 링크로
구글 수신 문제 해결법
메일은 이런 식으로 구현하는 거군요!!