0. 구글 계정 설정
Spring Mail로 이메일을 발송하기 위해서는 구글 계정에서 2단계 인증과 앱 비밀번호를 설정 해야한다.
Google 계정 관리 > 보안 > Google에 로그인하는 방법 > 2단계 인증
2단계 인증을 활성화한 뒤, 클릭해서 맨 아래를 보면 '앱 비밀번호'라는 항목이 있다.
이곳에서 새로운 앱 비밀번호를 설정한다.
'앱 선택 > 기타'를 선택하고 사용하고자 하는 이름을 설정한다. (중요하진 않다.)
생성을 클릭하면 화면에 16자리의 앱 비밀번호가 나타난다.
Spring Mail을 설정할 때 username에 이 구글 메일 주소, 그리고 password에 지금 발급받은 앱 비밀번호를 사용한다.
1. properties 설정
properties 파일과 설정 클래스를 생성한다.
앞서 말했 듯 password에는 16자리의 앱 비밀번호를 입력한다.
spring.mail.host=smtp.gmail.com
spring.mail.port=465
spring.mail.username=아이디@gmail.com
spring.mail.password=앱비밀번호
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.ssl.trust=smtp.gmail.com
나는 이 properties 파일을 외부파일로 뺐기 때문에 @Configuration 클래스를 따로 생성했다.
package com.chordncode.springmvcboard.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource(
value="file:${user.home}/Desktop/dev/springmail.properties",
ignoreResourceNotFound = true
)
public class MailConfig {
@Value("${spring.mail.host}")
private String host;
@Value("${spring.mail.port}")
private int port;
@Value("${spring.mail.username}")
private String username;
@Value("${spring.mail.password}")
private String password;
@Value("${spring.mail.properties.mail.smtp.auth}")
private boolean auth;
@Value("${spring.mail.properties.mail.smtp.ssl.enable}")
private boolean enable;
@Value("${spring.mail.properties.mail.smtp.ssl.trust}")
private String trust;
}
2. 메일 발송 클래스 생성
SimpleMailMessage로 메일을 작성하고 JavaMailSender 클래스를 사용해 메일을 발송한다.
package com.chordncode.springmvcboard.data.util;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
@Component
public class MailUtil {
private JavaMailSender mailSender;
public MailUtil(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail(String recipient, String subject, String body){
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(recipient);
message.setSubject(subject);
message.setText(body);
mailSender.send(message);
}
}
'Java > Spring Boot' 카테고리의 다른 글
[Spring Boot] JSP 사용하기 (0) | 2023.04.12 |
---|---|
[Spring Boot] JpaRepository의 쿼리 메서드 자동 구현 (0) | 2023.04.11 |
[Spring Boot] JpaRepository에서 @Query 사용하기 (0) | 2023.04.10 |
[Spring Boot] JPA의 Entity에서 1대N 관계 설정 (0) | 2023.04.10 |
[Spring Boot] JPA의 복합키 (0) | 2023.04.09 |