JavaMail API는 SMTP, IMAP, POP3 등 다양한 프로토콜을 사용하여 자바에서 이메일을 보내고, 받으며 관리할 수 있도록 하는 라이브러리이다.그중 SMTP 프로토콜을 사용하여 Spring MVC에서 이메일을 전송해 볼 것이다.
*SMTP(Simple Mail Transfer Protocol) : 이메일을 전송하는 데 사용되는 프로토콜
1. JavaMail API 의존성 추가하기
https://mvnrepository.com/artifact/javax.mail/javax.mail-api
https://mvnrepository.com/artifact/com.sun.mail/javax.mail
위 두 개의 링크에 들어가서 각각 1.6.2 버전을 선택 Maven을 복사하여 pom.xml에 붙여넣어 의존성을 추가시켜야 한다.
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
javax.mail
은 JavaMail API의 인터페이스를 제공하고, 이메일 관련 기능을 정의한다.
com.sun.mail
은 JavaMail API의 실제 구현체로, 이메일을 전송하고 수신하는 기능을 수행한다.
2. 이메일 환경설정(네이버 기준)
네이버 메일 > 환경설정에 들어가서 POP3/IMAP 설정에 들어간다.
POP3/SMTP 랑 IMAP/SMTP로 나누어져 있는데, SMTP를 사용할 예정이므로 둘 중 아무거나 하여도 상관없을 것이라고 생각한다.
* POP3와 IMAP의 차이 : POP3는 다운로드된 장치에서만 이메일에 액세스 할 수 있고, IMAP은 서버에 이메일이 저장되어서 모든 장치에서 이메일에 액세스 할 수 있다.
사용함을 체크해 주고 저장해 주면 된다.
나중에 필요한 부분은 SMTP 서버명과 SMTP 포트 넘버 부분이다.
3. root-context.xml 에 의존성 주입하기
<bean id="mailService" class="org.pj.service.EmailService"/>
org.pj.service.EmailService
에는 해당 클래스 위치를 적어주면 된다.
4. 코드 작성
JSP
<form action="${pageContext.request.contextPath}/mail" method="post" id="emailSend">
<input name="recipient" value="받는 사람 이메일 주소">
<input name="subject" value="안녕하세요.">
<textarea id="orderContent" name="content"></textarea>
<input type="submit" value="이메일 발송">
</form>
Service
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class EmailService {
private String host = "smtp.naver.com"; // 이메일을 전송할 SMTP 서버의 주소
private String username = "0000@naver.com"; // 발신자 이메일
private String password = "0000"; // 발신자 비밀번호
public void sendMail(String to, String subject, String content) {
Properties props = new Properties(); // 이메일 전송을 위한 속성을 설정하기 위한 Properties 객체를 생성
props.put("mail.smtp.auth", "true"); // SMTP 서버에 인증이 필요하다는 설정
props.put("mail.smtp.host", host); // 사용할 SMTP 서버 설정
props.put("mail.smtp.port", "465"); // SSL을 사용하는 SMTP 포트 설정
props.put("mail.smtp.ssl.enable", "true"); // SSL 암호화 활성화
// 이메일 세션 생성
// Authenticator를 사용하여 발신자의 이메일 주소와 비밀번호를 제공하여 인증
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session); // 새로운 이메일 메시지 생성
message.setFrom(new InternetAddress(username)); // 발신자의 이메일 주소 설정
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // 수신자의 이메일 주소 설정
message.setSubject(subject); // 이메일 제목 설정
message.setText(content); // 이메일 내용 설정
Transport.send(message); // 이메일 전송
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Controller
import org.inventory_pj.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class EmailController {
@Autowired
private EmailService emailService;
@PostMapping("/mail")
public String sendMail(@RequestParam("recipient") String recipient, @RequestParam("subject") String subject, @RequestParam("content") String content) {
emailService.sendMail(recipient, subject, content);
return "redirect:/";
}
}
5. 결과
'Spring' 카테고리의 다른 글
[IntelliJ] Spring Boot 프로젝트 생성 (0) | 2025.01.22 |
---|---|
[Spring MVC] 네이버 로그인 API _ Javascript 사용 (0) | 2022.11.21 |
[Spring MVC] 로그인하기 (0) | 2022.11.17 |