헤르메스 LIFE

[Open Source] Send Mail + 첨부파일 포함 본문

Spring Framework

[Open Source] Send Mail + 첨부파일 포함

헤르메스의날개 2011. 9. 22. 13:44
728x90
package common.util;  import util.CommonProperties;  import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.List; import java.util.Properties;  import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.SendFailedException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart;  import org.apache.log4j.Logger;  public class SendMail {     /**      * Logger      */     private static final Logger      logger   = Logger.getLogger(SendMail.class);          //static String msgText = "This is a message body.\nHere's the second line.777777";     //----- 변수 선언 ----------------------------     private String result_code = "";     private String fromAddr    = "";     private String host        = "";     private String sendName    = "";     private String mailTestYn  = "";     private String mailTestMail= "";     private String debugArg    = "";      //-----------------------------------------       public SendMail() {     	try { 	    	CommonProperties commProp = CommonProperties.getInstance(); 	        host = commProp.getProperty("SMTP_HOST"); 	        mailTestYn = commProp.getProperty("MAIL_TEST_YN"); 	        fromAddr = commProp.getProperty("ADMIN_EMAIL"); 	        sendName = commProp.getProperty("MAIL_NAME"); 	        mailTestMail = commProp.getProperty("MAIL_TEST_EMAIL");     		 	        logger.info("mailTestYn :: " + mailTestYn); 	        logger.info("mailTestMail :: " + mailTestMail); 	        debugArg = "false";     	} catch(Exception e) {     		e.printStackTrace();     	}     }      public static void main(String[] args) {         SendMail sm = new  SendMail();                   String subject1  = "단일 메일 테스트 메일입니다.";          StringBuffer strbuff = new StringBuffer();                  strbuff.append("");         strbuff.append("
테스트 메일입니다.

  ");         strbuff.append("잘 보내지는지 모르겠네요.
  
 ");         strbuff.append("잘 보내지나요..? 
  ");         strbuff.append("");                  String contents = strbuff.toString();                  sm.setFrom("aa002@test.com");         sm.setSendName("홍길동");         String send_email_return1 = sm.sendMail("aa002@test.com", "홍길동", subject1, contents) ;  // 개발메일 테스트         //String send_email_return1 = sm.sendMail("hrismaster@test.com", "홍길동", subject1, contents) ;   // 운영메일 테스트         logger.info("단일 send_email RETURN : "+ send_email_return1);                  String send_email_return2 = sm.sendMailWithFile("aa002@test.com", "허균", subject1, contents, "C:\\은행이체파일_August_salary(from-Skens).xls") ;         logger.info("단일 send_email RETURN : "+ send_email_return2); /*         String subject2  = "대량 메일 테스트 메일입니다.";                 List addrList = new ArrayList();         String[] str1 = { "홍길동", "test2000@lycos.co.kr" };         addrList.add(str1);         String[] str2 = { "홍길동", "testwing@naver.com" };         addrList.add(str2);         String[] str3 = { "홍길동", "test@aaaa.co.kr" };         addrList.add(str3);                  sm.setFrom("test2000@lycos.co.kr");         sm.setSendName("홍길동");                  String send_email_return2 = sm.sendMailList(addrList, subject2, contents) ;         logger.info("대량 send_email RETURN : "+ send_email_return2); */     }      /**      * 발송자 메일 주소를 셋팅한다.      *      * @param str 발송자 메일주소      */     public void setFrom(String str) {         this.fromAddr = str;     }          /**      * 발송자명을 셋팅한다.      *      * @param str 발송자명      */     public void setSendName(String str) {         this.sendName = str;     }      /**      * 한사람에게 메일을 발송한다.      *       * @param mail_addr   송신주소      * @param name        송신자명      * @param title       제목      * @param contents    내용      */     public String sendMail(String mail_addr, String name, String title, String contents) {          boolean debug = Boolean.valueOf(debugArg).booleanValue();          // create some properties and get the default Session         Properties props = new Properties();         props.put("mail.smtp.host", host);         props.put("mail.smtp.auth", "true");                  // 반드시 프로퍼티에 세팅되어 있어야 한다. 아니면 인증을 시도하지 않는다.          Authenticator auth = new MyAuthentication();          if (debug) props.put("mail.debug", debugArg);          // 기본 Session을 생성하고 할당합니다.         Session session = Session.getInstance(props, auth);         session.setDebug(debug);          // system.properties 파일에 아래의 설정이 있으면         // MAIL_TEST_YN=Y         // MAIL_TEST_EMAIL=aa002@test.com         // 테스트 계정으로 메일을 발송함.         if(mailTestYn.equals("Y")) mail_addr = mailTestMail;                  try {             // 받는 사람의 메일 주소를 설정합니다.             InternetAddress address = new InternetAddress(mail_addr, name);                             // essage 클래스의 객체를 Session을 이용하여 생성합니다.             //Message msg = new MimeMessage(session);             MimeMessage msg = new MimeMessage(session);             msg.addHeader("Content-Transfer-Encoding","base64");   // base64 처리              msg.setRecipient(Message.RecipientType.TO, address);                          //보내는 사람의 이름과 메일주소를 설정합니다.             //msg.setFrom(new InternetAddress(from, from));             //msg.setFrom(new InternetAddress(new String(this.sendName.getBytes("euc-kr"), "8859_1") + "<" + fromAddr + ">"));             //msg.setFrom(new InternetAddress(new String(this.sendName.getBytes("euc-kr"), "utf-8") + "<" + fromAddr + ">"));             msg.setFrom(new InternetAddress(fromAddr, this.sendName + "<" + fromAddr + ">", "utf-8"));                          // 제목을 설정합니다.             //msg.setSubject(title);             //msg.setSubject(new String(title.getBytes("euc-kr"), "8859_1"));             //msg.setSubject(new String(title.getBytes("euc-kr"), "utf-8"));             msg.setSubject(title, "utf-8");             msg.setSentDate(new Date());              // If the desired charset is known, you can use             // setText(text, charset)             //msg.setContent(contents, "text/html; charset=euc-kr");             msg.setContent(contents, "text/html; charset=utf-8");             //msg.setText(contents);              // 설정보존             msg.saveChanges();                          Transport.send(msg);                          result_code = "Y";         } catch (MessagingException mex) {             logger.info("\n--Exception handling in SendMail.java");             mex.printStackTrace();              Exception ex = mex;             do {                 if (ex instanceof SendFailedException) {                     SendFailedException sfex = (SendFailedException) ex;                     Address[] invalid = sfex.getInvalidAddresses();                     if (invalid != null) {                         logger.info("    ** Invalid Addresses");                         if (invalid != null) {                             for (int i = 0; i < invalid.length; i++)                                 logger.info("         " + invalid[i]);                         }                     }                     Address[] validUnsent = sfex.getValidUnsentAddresses();                     if (validUnsent != null) {                         logger.info("    ** ValidUnsent Addresses");                         if (validUnsent != null) {                             for (int i = 0; i < validUnsent.length; i++)                                 logger.info("         " + validUnsent[i]);                         }                     }                     Address[] validSent = sfex.getValidSentAddresses();                     if (validSent != null) {                         logger.info("    ** ValidSent Addresses");                         if (validSent != null) {                             for (int i = 0; i < validSent.length; i++)                                 logger.info("         " + validSent[i]);                         }                     }                 }                  if (ex instanceof MessagingException) ex = ((MessagingException) ex).getNextException();                 else                     ex = null;             } while (ex != null);                          result_code = "N";         } catch(UnsupportedEncodingException uee) {             logger.error(uee.getMessage());         }          return result_code;     }          /**      * 한사람에게 메일을 발송한다. (첨부파일 포함.)      *       * @param mail_addr   송신주소      * @param name        송신자명      * @param title       제목      * @param contents    내용      * @param withFile    경로포함된 파일명(예:c:\temp\파일.xls)      */     public String sendMailWithFile(String mail_addr, String name, String title, String contents, String withFile) {          boolean debug = Boolean.valueOf(debugArg).booleanValue();          // create some properties and get the default Session         Properties props = new Properties();         props.put("mail.smtp.host", host);         props.put("mail.smtp.auth", "true");                  // 반드시 프로퍼티에 세팅되어 있어야 한다. 아니면 인증을 시도하지 않는다.          Authenticator auth = new MyAuthentication();          if (debug) props.put("mail.debug", debugArg);          // 기본 Session을 생성하고 할당합니다.         Session session = Session.getInstance(props, auth);         session.setDebug(debug);          // system.properties 파일에 아래의 설정이 있으면         // MAIL_TEST_YN=Y         // MAIL_TEST_EMAIL=aa002@test.com         // 테스트 계정으로 메일을 발송함.         if(mailTestYn.equals("Y")) mail_addr = mailTestMail;                  String attFile = java.net.URLDecoder.decode(withFile);                  try {             // 받는 사람의 메일 주소를 설정합니다.             InternetAddress address = new InternetAddress(mail_addr, name);                             // essage 클래스의 객체를 Session을 이용하여 생성합니다.             //Message msg = new MimeMessage(session);             MimeMessage msg = new MimeMessage(session);             msg.addHeader("Content-Transfer-Encoding","base64");   // base64 처리              msg.setRecipient(Message.RecipientType.TO, address);                          //보내는 사람의 이름과 메일주소를 설정합니다.             //msg.setFrom(new InternetAddress(from, from));             //msg.setFrom(new InternetAddress(new String(this.sendName.getBytes("euc-kr"), "8859_1") + "<" + fromAddr + ">"));             msg.setFrom(new InternetAddress(fromAddr, this.sendName + "<" + fromAddr + ">", "utf-8"));             // 제목을 설정합니다.             //msg.setSubject(title);             msg.setSubject(title, "utf-8");                          //Multipart 객체를 생성합니다. 			Multipart multiPart = new MimeMultipart(); 			             //파일이 있을 경우를 생각해서 MimeBodyPart객체를 생성합니다. 			MimeBodyPart contentsBodyPart = new MimeBodyPart(); 			//contentsBodyPart.setContent(contents, "text/html; charset=euc-kr"); 			contentsBodyPart.setContent(contents, "text/html; charset=utf-8");              			multiPart.addBodyPart(contentsBodyPart); 			 			if(withFile.length() > 0) { 				MimeBodyPart fileBodyPart = new MimeBodyPart(); 		        FileDataSource fds = new FileDataSource(attFile); 		        fileBodyPart.setDataHandler(new DataHandler(fds)); 				//한글파일일 경우를 생각해서 다시 KSC5601에서 8859_1로 변환시킵니다. 		        fileBodyPart.setFileName(new String(fds.getName().getBytes("euc-kr"), "8859_1")); //				mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr","B"));   		        multiPart.addBodyPart(fileBodyPart);  			} 			 			msg.setContent(multiPart);             msg.setSentDate(new Date());              // If the desired charset is known, you can use             // setText(text, charset)                          //msg.setText(contents);                            Transport.send(msg);                          result_code = "Y";         } catch (MessagingException mex) {             logger.info("\n--Exception handling in msgsendsample.java");             mex.printStackTrace();              Exception ex = mex;             do {                 if (ex instanceof SendFailedException) {                     SendFailedException sfex = (SendFailedException) ex;                     Address[] invalid = sfex.getInvalidAddresses();                     if (invalid != null) {                         logger.info("    ** Invalid Addresses");                         if (invalid != null) {                             for (int i = 0; i < invalid.length; i++)                                 logger.info("         " + invalid[i]);                         }                     }                     Address[] validUnsent = sfex.getValidUnsentAddresses();                     if (validUnsent != null) {                         logger.info("    ** ValidUnsent Addresses");                         if (validUnsent != null) {                             for (int i = 0; i < validUnsent.length; i++)                                 logger.info("         " + validUnsent[i]);                         }                     }                     Address[] validSent = sfex.getValidSentAddresses();                     if (validSent != null) {                         logger.info("    ** ValidSent Addresses");                         if (validSent != null) {                             for (int i = 0; i < validSent.length; i++)                                 logger.info("         " + validSent[i]);                         }                     }                 }                  if (ex instanceof MessagingException) ex = ((MessagingException) ex).getNextException();                 else                     ex = null;             } while (ex != null);                          result_code = "N";         } catch(UnsupportedEncodingException uee) {             logger.error(uee.getMessage());         }          return result_code;     }          /**      * 다수자에게 메일을 발송한다.      * List에는 배열이 담겨있다.      *       * @param mailList   사용자 메일 정보 목록      * @param title      제목      * @param contents   내용      * @return      *       *
     * List addrList = new ArrayList();      * String name = rs.getString("NAME") == null ? "" : rs.getString("NAME").trim();      * String addr = rs.getString("MAIL_ADDR") == null ? "" : rs.getString("MAIL_ADDR").trim();      * String[] str = { name, addr };      * addrList.add(str);      * 
*/ public String sendMailList(List mailList, String title, String contents) { boolean debug = Boolean.valueOf(debugArg).booleanValue(); // create some properties and get the default Session Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.auth", "true"); // 반드시 프로퍼티에 세팅되어 있어야 한다. 아니면 인증을 시도하지 않는다. Authenticator auth = new MyAuthentication(); if (debug) props.put("mail.debug", debugArg); Session session = Session.getInstance(props, auth); session.setDebug(debug); try { InternetAddress[] address = new InternetAddress[mailList.size()]; for(int i = 0; i < mailList.size(); i++) { String [] addr = (String[]) mailList.get(i); address[i] = new InternetAddress(addr[1], addr[0]); } Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(new String(this.sendName.getBytes("euc-kr"), "8859_1") + "<" + fromAddr + ">")); //InternetAddress[] address = {new InternetAddress(arg[0])}; msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject(title); msg.setSentDate(new Date()); // If the desired charset is known, you can use // setText(text, charset) msg.setContent(contents, "text/html; charset=euc-kr"); //msg.setText(contents); Transport.send(msg); result_code = "Y"; } catch (MessagingException mex) { logger.info("\n--Exception handling in msgsendsample.java"); mex.printStackTrace(); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { logger.info(" ** Invalid Addresses"); if (invalid != null) { for (int i = 0; i < invalid.length; i++) logger.info(" " + invalid[i]); } } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { logger.info(" ** ValidUnsent Addresses"); if (validUnsent != null) { for (int i = 0; i < validUnsent.length; i++) logger.info(" " + validUnsent[i]); } } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { logger.info(" ** ValidSent Addresses"); if (validSent != null) { for (int i = 0; i < validSent.length; i++) logger.info(" " + validSent[i]); } } } if (ex instanceof MessagingException) ex = ((MessagingException) ex).getNextException(); else ex = null; } while (ex != null); result_code = "N"; } catch(UnsupportedEncodingException uee) { logger.error(uee.getMessage()); } return result_code; } } class MyAuthentication extends Authenticator { PasswordAuthentication pa; public MyAuthentication() { //CommonProperties commProp = CommonProperties.getInstance(); //String MAIL_AUTH_ID = commProp.getProperty("MAIL_AUTH_ID"); //String MAIL_AUTH_PW = commProp.getProperty("MAIL_AUTH_PW"); String MAIL_AUTH_ID = "AA002"; String MAIL_AUTH_PW = "AA002"; pa = new PasswordAuthentication(MAIL_AUTH_ID, MAIL_AUTH_PW); // 여러분들이 사용하고 있는 smtp server의 아이디와 패스워드를 입력한다. } // 아래의 메소드는 시스템측에서 사용하는 메소드이다. public PasswordAuthentication getPasswordAuthentication() { return pa; } }

 

728x90