Java - Mail 보내기

Programming/Java 2016.03.12 16:22 Posted by 파란크리스마스

출처 : 자바에서 메일 보내는 방법 - Nothing New Under the Sun

JavaMail 다운로드

다운로드

Servlet 소스

class mvc.servlet.MailServlet

package mvc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

@WebServlet(urlPatterns = "/mail")
public class MailServlet extends HttpServlet {

	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String from_email = request.getParameter("from_email");
		String to_email = request.getParameter("to_email");
		String mail_subtitle = request.getParameter("subtitle");
		String mail_content = request.getParameter("content");
		
		System.out.println("from_email = " + from_email);
		System.out.println("to_email = " + to_email);
		
		
		// 먼저 환경 정보를 설정해야 한다.
		// 메일 서버 주소를 IP 또는 도메인 명으로 지정한다.
		Properties props = System.getProperties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", "smtp.gmail.com");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.smtp.quitwait", "false");
		
		Authenticator auth = new MyAuthenticator();

		// 위 환경 정보로 "메일 세션"을 만들고 빈 메시지를 만든다
		Session session = Session.getDefaultInstance(props, auth);
		session.setDebug(true);
		
		MimeMessage msg = new MimeMessage(session);
		
		try {
			// 발신자, 수신자, 참조자, 제목, 본문 내용 등을 설정한다
			msg.setFrom(new InternetAddress(from_email, "*보내는사람*"));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to_email, "*받는사람*"));
			/*
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress("eee@fff.co.kr", "선덕여왕"));
			msg.addRecipient(Message.RecipientType.CC, new InternetAddress("ggg@hhh.co.kr", "의자왕"));
			*/
			msg.setSubject(mail_subtitle);
			msg.setContent(mail_content, "text/html; charset=utf-8");

			// 메일을 발신한다
			Transport.send(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		response.setContentType("text/x-json;charset=UTF-8");            
		response.setHeader("Cache-Control", "no-cache"); 
		
		PrintWriter out = response.getWriter();
		
		JSONObject json = new JSONObject();
		json.put("result", "true");
		out.println(json);
	}
	
	static class MyAuthenticator extends Authenticator {
		public PasswordAuthentication getPasswordAuthentication() {
			//String username = "******@gmail.com";
			//String password = "*****";
			return new PasswordAuthentication(username, password);
		}
	}
}

mail.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="../resources/js/jquery-1.12.0.js"></script>
<title>Java Mail</title>
<style type="text/css">
body {
	font-family: 'Apple SD Gothic Neo',arial,sans-serif;
	font-size: 14px;
}
</style>
</head>
<body>
	
<form action="mail">
	<table>
		<tr><td>보내는사람</td><td><input type="text" name="from_email"></td></tr>
		<tr><td>받는사람</td><td><input type="text" name="to_email"></td></tr>
		<tr><td>제목</td><td><input type="text" name="subtitle"></td></tr>
		<tr><td>내용</td><td><input type="text" name="content"></td></tr>
	</table>
	<input type="submit" value="보내기">
</form>

</body>
</html>

인증오류 해결방법

출처 : email - how to fix "send-mail: Authorization failed 534 5.7.14

534 5.7.14  https://support.google.com/mail/answer/78754 g23sm18237842pfg.35 - gsmtp

	at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:823)
	at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:756)
	at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:673)
	at javax.mail.Service.connect(Service.java:317)
	at javax.mail.Service.connect(Service.java:176)
	at javax.mail.Service.connect(Service.java:125)
	at javax.mail.Transport.send0(Transport.java:194)
	at javax.mail.Transport.send(Transport.java:124)
	at mvc.servlet.MailServlet.service(MailServlet.java:54)

https://www.google.com/settings/security/lesssecureapps

보안 수준이 낮은 앱의 액세스 을 사용으로 설정

AJAX로 보내기

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="resources/js/jquery-1.12.0.js"></script>
<title>Java Mail</title>
<style type="text/css">
body {
	font-family: 'Apple SD Gothic Neo',arial,sans-serif;
	font-size: 14px;
}
</style>
<script type="text/javascript">
function sendEMail() {
	
	var form = document.formEMail;

	//
	try {
		$.ajax({
			type: 'GET',
			url: 'mail',
			dataType: 'json',
			data: {
				from_email : form.from_email.value,
				to_email : form.to_email.value,
				subtitle : form.subtitle.value,
				content : form.content.value
			},
			success: function(data)
			{
				//alert(data);
				$('.clsResult').html(data.result);
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				alert('There was an error.');
			}
		});
		
	} catch(e) {
		alert(e);
	}
	
	return false;
}

</script>
</head>
<body>
	
<form action="mail" name="formEMail">
	<table>
		<tr><td>보내는사람</td><td><input type="text" name="from_email"></td></tr>
		<tr><td>받는사람</td><td><input type="text" name="to_email"></td></tr>
		<tr><td>제목</td><td><input type="text" name="subtitle"></td></tr>
		<tr><td>내용</td><td><input type="text" name="content"></td></tr>
	</table>
	<input type="submit" value="보내기">
</form>

<hr>

<button onclick="javascript:sendEMail();">AJAX로 보내기</button><br/>
<p>결과</p>
<div class="clsResult">
</div>

</body>
</html>
저작자 표시
신고


 

티스토리 툴바