Java Mail/Email, Web

Email Sending Web Project

Soul-Learner 2011. 7. 18. 15:37
Gmail SMTP 서버와 JavaMail1.4 를 이용하여 웹에서 메일 보내기 프로젝트 예제

환경: JDK1.6, Tomcat 6, Eclipse 3.5, JavaMail 1.4
참고: JAF 라이브러리는 JDK6에 포함되어 있기 때문에 별도로 다운로드할 필요가 없지만 간혹 Eclipse에 라이브러리를 설정하고 Tomcat 과 연동할 경우에는 Tomcat측에서 activation.jar를 찾지 못하여 ClassNotFoundException이 발생하는 경우가 있다. 이런 경우에는 mail.jar, activation.jar를 Tomcat/common/lib/ 안에 복사해 주면 된다.

mailForm.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>메일 보내기 폼</title>
<style>
 form{ border:1px solid grey; width: 500px;}
 caption { margin-top:10px; margin-bottom: 10px; font-size: 18pt; }
 th { text-align: right; width:120px;}
 td { text-align: left; }
 .btn { text-align: center; }
 textarea { width:380px; }
 input.text{ width:380px; }
 input.btn { width:70px; }
 table { padding: 10 10 10; margin-right:10px; }
</style>
</head>
<body><br/><br/>
<center>
 <form action="MailServlet" method="post">
  <input type="hidden" name="cmd" value="send"/>
 <table border="1" cellspacing="0" rules="none">
  <caption>메일 쓰기</caption>
  <tr><th>제 목</th><td><input class="text" type="text" name="subject" value="메일보내기 연습"/></td></tr>
  <tr><th>보내는 사람</th><td><input class="text"  type="text" name="from" value="myid@micropilot.co.kr"/></td></tr>
  <tr><th>받는 사람</th><td><input class="text"  type="text" name="to" value="naver_id@naver.com"/></td></tr>
  <tr><th>내 용</th><td><textarea name="msg" rows="5" cols="20">잘 들어가야 할텐데....</textarea></tr>
  <tr><td colspan="2"> </td></tr>
  <tr><td colspan="2" style="text-align:center; padding-bottom: 10px;">
   <input type="submit" value="메일전송"/>
   <input type="reset" value="취 소"/> </td></tr>
 </table>
 </form>
</center>
</body>
</html>



MailServlet.java

package mail;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;

import bean.GmailBean;

public class MailServlet extends HttpServlet{

 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse resp)
   throws ServletException, IOException {
  
  request.setCharacterEncoding("euc-kr");
  String cmd = request.getParameter("cmd");
  
  if(cmd.equals("send")) {
   String subject = request.getParameter("subject");
   String from = request.getParameter("from");
   String to = request.getParameter("to");
   String msg = request.getParameter("msg");
   
   GmailBean gmail = new GmailBean();
   gmail.setSubject(subject);
   gmail.setFrom(from);
   gmail.setTo(to);
   gmail.setMsg(msg);
   boolean ok = gmail.send();
   
   request.setAttribute("result", ok);
   request.getRequestDispatcher("/sendResult.jsp").forward(request, resp);
  }
 }
 
}


GmailBean.java

package bean;

import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;

public class GmailBean {
 
 private String subject;
 private String from;
 private String to;
 private String msg;
 
 private Session session;
 
 public GmailBean() {
  createSession();
 }
 
 private void createSession(){
   Properties p = new Properties();
   p.put("mail.smtp.user", "myid@gmail.com"); // Google계정@gmail.com으로 설정
   p.put("mail.smtp.host", "smtp.gmail.com");
   p.put("mail.smtp.port", "465");
   p.put("mail.smtp.starttls.enable","true");
   p.put( "mail.smtp.auth", "true");

   p.put("mail.smtp.debug", "true");
   p.put("mail.smtp.socketFactory.port", "465");
   p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
   p.put("mail.smtp.socketFactory.fallback", "false");
   try {
     Authenticator auth = new SMTPAuthenticator();
     this.session = Session.getInstance(p, auth);
     this.session.setDebug(true);
   }catch (Exception e) {
  e.printStackTrace();
   }
 }
 
 public boolean send(){
  try{
     MimeMessage msg = new MimeMessage(session);
     String message = "Gmail SMTP 서버를 이용한 JavaMail 테스트";
     msg.setSubject("Gmail SMTP 서버를 이용한 JavaMail 테스트");
     Address fromAddr = new InternetAddress(from); // 보내는 사람의 메일주소
     msg.setFrom(fromAddr);
     Address toAddr = new InternetAddress(to);  // 받는 사람의 메일주소
     msg.addRecipient(Message.RecipientType.TO, toAddr);
     msg.setContent(message, "text/plain;charset=KSC5601");
     Transport.send(msg);
     return true;
   }
   catch (Exception mex) {
     mex.printStackTrace();
   }
   return false;
 }
 
 public String getSubject() {
  return subject;
 }
 public String getFrom() {
  return from;
 }
 public String getTo() {
  return to;
 }
 public String getMsg() {
  return msg;
 }
 public void setSubject(String subject) {
  this.subject = subject;
 }
 public void setFrom(String from) {
  this.from = from;
 }
 public void setTo(String to) {
  this.to = to;
 }
 public void setMsg(String msg) {
  this.msg = msg;
 }
}

class SMTPAuthenticator extends javax.mail.Authenticator {

  public PasswordAuthentication getPasswordAuthentication() {
   return new PasswordAuthentication("cwiskykim", "cw*****"); // Google id, pwd, 주의) @gmail.com 은 제외하세요
  }
}


sendResult.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
 boolean ok = (Boolean)request.getAttribute("result");
 String msg = null; 
 if(ok) msg = "성공적으로 메일을 전송했습니다";
 else msg = "메일을 보내는 중에 오류가 발생했습니다";
%>
<script>
 alert("<%=msg%>");
</script>