2023-11-16,   이현지

본 포스팅은 JavaMail을 이용한 메일 전송에 대한 내용입니다.

JavaMail

전자 메일을 간편하게 주고 받을 수 있도록 하는 Java API입니다.
POP, IMAP, SMTP와 같은 이메일 프로토콜을 지원하며, 이메일 생성 및 전송 작업에 필요한 여러 기능을 제공합니다.

예제

사전 설정

POP, SMTP, IMAP 사용 허용

JavaMail을 이용해 전자 메일을 발송하기 위해선 우선 발신자 계정의 POP, SMTP, IMAP 사용 허용 설정을 해야 합니다.

GMail 예시

GMail - POP, IMAP, SMTP 허용

2단계 인증 후 앱 비밀번호 생성 (구글만 해당)

구글의 경우 SMTP 메일 전송 시 2단계 인증 후 발급 가능한 앱 비밀번호가 필요합니다.
앱 비밀번호 생성 방법은 아래와 같습니다.

  • Google 계정관리 페이지 - [보안] - [로그인 2단계 인증 사용]

2단계 인증

  • [로그인 2단계 인증] - [앱 비밀번호] - 앱 비밀번호를 사용할 앱(메일)과 기기 선택 후, [생성] 클릭

앱비밀번호 생성

  • 생성된 16자리 앱 비밀번호를 복사하여 별도로 보관

앱비밀번호



1. 프로젝트 생성 및 의존성 추가

Spring Starter Project 생성 후 JavaMail 의존성을 추가해줍니다.

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
</dependency>

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>javax.mail-api</artifactId>
</dependency>



2. Session

Session 클래스는 이메일 서버와의 연결을 수행합니다.
발신자 계정 아이디, 암호, 메일 서버 관련 설정(SMTP 호스트 주소, 포트, 인증, 보안 등..)이 가능합니다.
서버 설정의 경우 각 이메일 서버마다 지원하고 규정하는 설정이 다르므로 확인 후 설정하시기 바랍니다.

GMail 예시

smtp 호스트 주소 (mail.smtp.host) : smtp.gmail.com
TLS/STARTTLS 포트 (mail.smtp.port) : 587
인증 필요 (mail.smtp.auth) : 예
TLS 사용 가능 여부 (mail.smtp.starttls.enable) : 예
SSL 사용 가능 여부 (mail.smtp.ssl.enable) : 예

또한 SSL 보안의 경우 여러 보안 약점이 있으므로 가급적 TLS 보안을 사용하는 것이 좋습니다.

// 발신자 메일 주소
String sender = "발신자 메일 주소";
// 발신자 메일 계정 암호
String pwd = "발신자 메일 계정 암호";

// Properties 생성
Properties prop = new Properties();
// Property에 SMTP 서버 정보 설정
props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");  	// SMTP 서비스 주소     	
props.put("mail.smtp.port", 587);				    // 서비스 포트 설정
props.put("mail.smtp.auth", "true");				// SMTP 인증 설정         
props.put("mail.smtp.starttls.enable", "true");	    // TLS 보안        	
//  props.put("mail.smtp.ssl.enable", "true");       // SSL 보안

// Session 생성
Session session = Session.getDefaultInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(sender, pwd);
        }
});



3. MimeMessage

MimeMessage 클래스는 MIME(Multipurpose Internet Mail Extensions) 타입 메시지를 다룹니다.
MIME 타입 메시지는 텍스트, 첨부파일, HTML 등을 포함합니다.

// MimeMessage 생성
MimeMessage message = new MimeMessage(session);



4. MimeMessageHelper

MimeMessageHelper는 MimeMessage를 더 쉽게 다룰 수 있게 스프링 프레임워크에서 제공하는 클래스입니다.
발신자, 수신자, 제목, 본문 설정 및 파일 첨부나 HTML 본문 추가 같은 작업을 간단히 수행할 수 있습니다.

// MimeMessageHelper 생성
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");      

// 발신자 설정
helper.setFrom(new InternetAddress(sender));

// 수신자 설정
InternetAddress[] mailAddressArr = {
                                    new InternetAddress("recipient1@mail.com"),
                                    new InternetAddress("recipient2@mail.com"),
                                    new InternetAddress("recipient3@mail.com")
                                    };
helper.setTo(mailAddressArr);

// 메일 제목 설정
helper.setSubject("SMTP 메일 전송 테스트입니다.");       
// 메일 내용 설정
helper.setText("<!DOCTYPE html>\r\n"
                + "<html lang=\"en\">\r\n"
                + "<head>\r\n"
                + "    <meta charset=\"UTF-8\">\r\n"
                + "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\r\n"
                + "    <title>메일 템플릿</title>\r\n"
                + "</head>\r\n"
                + "<body>\r\n"
                + "    <h1 style=\"color:orange\">Hello World!</h1>\r\n"
                + "</body>\r\n"
                + "</html>", true); // true는 HTML 형식의 텍스트임을 나타냄



5. Transport

Transport 클래스의 send() 메소드는 이메일 전송을 위해 필요한 작업(서버 연결, 메일 전송, 서버 연결 해제.. 등)을 수행하며 MimeMessage 객체를 받아 이메일 메시지를 전송합니다.

// 메일 발송
Transport.send(message); 
System.out.println("메일 발송 완료");



이상으로 JavaMail을 이용한 메일 전송에 대한 포스팅을 마치겠습니다.



Reference

  • https://support.google.com/mail/answer/7104828?hl=ko&sjid=14729820917103750996-AP

업데이트: