16 SMTP를 활용한 이메일 전송하기

알재·2023년 7월 25일
0

JSP & Servlet

목록 보기
16/16

16.1 프로젝트 구상

16.2 네이버 SMTP 설정

네이버를 SMTP 서버로 사용하기 위해 설정을 한다.

  • POP3(Post Office Protocol 3)
    클라이언트가 메일 서버에서 메일을 받아오는 프로토콜.
  • IMAP(Internet Message Access Protocol)
    메일 서버에서 메일을 내려받는 프로토콜. POP3와 다른점은 중앙 서버에서 동기화가 이루어져 같은 계정으로 연결된 모든 장치에서 똑같은 내용이 보임.

16.3 이메일 전송 프로그램 작성

16.3.1 이메일 작성 화면

EmailSendMain.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>   
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>SMTP 이메일 전송</title>
</head>
<body>
<h2>이메일 전송하기</h2>
<form method="post" action="SendProcess.jsp">
<table border=1>
    <tr>    
        <td>
            보내는 사람 : <input type="text" name="from" value="" />
        </td>
    </tr>
    <tr>    
        <td>
            받는 사람 : <input type="text" name="to" value="" />
        </td>
    </tr>
    <tr>    
        <td>
            제목 : <input type="text" name="subject" size="50" value="" />
        </td>
    </tr>
    <tr>    
        <td>
            형식 :
            <input type="radio" name="format" value="text" checked />Text
            <input type="radio" name="format" value="html" />HTML
        </td>
    </tr>
    <tr>
        <td>
            <textarea name="content" cols="60" rows="10"></textarea>
        </td>
    </tr>
    <tr>
        <td>
            <button type="submit">전송하기</button>
        </td>
    </tr>
</table>
</form>
</body>
</html>

16.3.2 이메일 전송 클래스 작성

NaverSMTP.java

package smtp;

import java.util.Map;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

// 네이버 SMTP 서버를 통해 이메일을 전송하는 클래스
public class NaverSMTP {
    private final Properties serverInfo; // 서버 정보
    private final Authenticator auth;    // 인증 정보

    public NaverSMTP() {
        // 네이버 SMTP 서버 접속 정보
        serverInfo = new Properties();
        serverInfo.put("mail.smtp.host", "smtp.naver.com");
        serverInfo.put("mail.smtp.port", "465");
        serverInfo.put("mail.smtp.starttls.enable", "true");
        serverInfo.put("mail.smtp.auth", "true");
        serverInfo.put("mail.smtp.debug", "true");
        serverInfo.put("mail.smtp.socketFactory.port", "465");
        serverInfo.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        serverInfo.put("mail.smtp.socketFactory.fallback", "false");

        // 사용자 인증 정보
        auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("네이버 아이디", "네이버 패스워드");
            }
        };
    }

    // 주어진 메일 내용을 네이버 SMTP 서버를 통해 전송합니다.
    public void emailSending(Map<String, String> mailInfo) throws MessagingException {
        // 1. 세션 생성
        Session session = Session.getInstance(serverInfo, auth);
        session.setDebug(true);

        // 2. 메시지 작성
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(mailInfo.get("from")));     // 보내는 사람
        msg.addRecipient(Message.RecipientType.TO,
                         new InternetAddress(mailInfo.get("to")));  // 받는 사람
        msg.setSubject(mailInfo.get("subject"));                    // 제목
        msg.setContent(mailInfo.get("content"), mailInfo.get("format"));  // 내용

        // 3. 전송
        Transport.send(msg);
    }
}

16.3.3 HTML 형식 메일 템플릿 준비

MailForm.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MustHave 메일 템플릿</title>
</head>
<body>
    <h2>MustHave 메일 템플릿</h2>
    <table border=1 width="100%">
        <tr>
            <td width="50">내용</td>
            <td>__CONTENT__</td>
        </tr>
        <tr>
            <td>이미지</td>
            <td><img src="https://github.com/goldenrabbit2020/musthave_jsp/blob/main/GOLDEN-RABBIT_LOGO_150.png?raw=true" alt="골든래빗" /></td>
        </tr>
    </table>
</body>
</html>

16.3.4 이메일 전송 처리 페이지 작성

SendProcess.jsp

<%@ page import="java.io.BufferedReader"%>
<%@ page import="java.io.FileReader"%>
<%@ page import="java.util.HashMap"%>
<%@ page import="java.util.Map"%>
<%@ page import="smtp.NaverSMTP"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
// 폼값(이메일 내용) 저장
Map<String, String> emailInfo = new HashMap<String, String>();
emailInfo.put("from", request.getParameter("from"));  // 보내는 사람
emailInfo.put("to", request.getParameter("to"));      // 받는 사람
emailInfo.put("subject", request.getParameter("subject"));  // 제목

// 내용은 메일 포맷에 따라 다르게 처리
String content = request.getParameter("content");  // 내용
String format = request.getParameter("format");    // 메일 포맷(text 혹은 html)
if (format.equals("text")) {
    // 텍스트 포맷일 때는 그대로 저장
    emailInfo.put("content", content);
    emailInfo.put("format", "text/plain;charset=UTF-8");
}
else if (format.equals("html")) {
    // HTML 포맷일 때는 HTML 형태로 변환해 저장
    content = content.replace("\r\n", "<br/>");  // 줄바꿈을 HTML 형태로 수정

    String htmlContent = ""; // HTML용으로 변환된 내용을 담을 변수
    try {
        // HTML 메일용 템플릿 파일 읽기
        String templatePath = application.getRealPath("/16EmailSend/MailForm.html");
        BufferedReader br = new BufferedReader(new FileReader(templatePath));

        // 한 줄씩 읽어 htmlContent 변수에 저장
        String oneLine;
        while ((oneLine = br.readLine()) != null) {
            htmlContent += oneLine + "\n";
        }
        br.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    // 템플릿의 "__CONTENT__" 부분을 메일 내용 대체 (변환 완료)
    htmlContent = htmlContent.replace("__CONTENT__", content);
    // 변환된 내용을 저장
    emailInfo.put("content", htmlContent);
    emailInfo.put("format", "text/html;charset=UTF-8");
}

try {
    NaverSMTP smtpServer = new NaverSMTP();  // 메일 전송 클래스 생성
    smtpServer.emailSending(emailInfo);      // 전송
    out.print("이메일 전송 성공");
}
catch (Exception e) {
    out.print("이메일 전송 실패");
    e.printStackTrace();
}
%>

16.4 동작 확인

Text형식 전송 테스트


HTML 형식 전송 테스트

profile
저장소

1개의 댓글

comment-user-thumbnail
2023년 7월 25일

정보 감사합니다.

답글 달기

관련 채용 정보