헤르메스 LIFE

[Open Source] Thread를 통한 Mail 발송 본문

Spring Framework

[Open Source] Thread를 통한 Mail 발송

헤르메스의날개 2011. 9. 22. 13:40
728x90
package common.util;  

import java.io.UnsupportedEncodingException; 
import java.util.Date; import java.util.HashMap; 
import java.util.Properties;  
import javax.mail.Address; 
import javax.mail.Authenticator; 
import javax.mail.MessagingException; 
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.MimeMessage;  
import org.apache.log4j.Logger;  

public class ThreadSendMail implements Runnable {
    private static Logger log = Logger.getRootLogger();
    private HashMap ctntHash = null;
    public ThreadSendMail(HashMap hashmap) {
    	ctntHash = hashmap;
    }      
    
    public static void sendMailA(HashMap hashmap) {
    	String host = hashmap.get("smtp_host").toString();
        String fromName = hashmap.get("from_name").toString();
        String fromAddr = hashmap.get("from").toString();
        String toAddr = hashmap.get("recipients").toString();
        String subject = hashmap.get("subject").toString();
        String content = hashmap.get("content").toString();
        log.debug((new StringBuilder("smtp_host[")).append(host).append("] from_name[").append(fromName).append("] from[").append(fromAddr).append("] recipients[").append(toAddr).append("] subject[").append(subject).append("]  ").toString());
        Authenticator auth = new MyAuthentication(hashmap.get("mail_auth_id").toString(), hashmap.get("mail_auth_pw").toString());
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        Session session = null;

        if(hashmap.get("mail_auth_id") != null && hashmap.get("mail_auth_pw") != null) {
        	props.put("mail.smtp.auth", "true");
            session = Session.getInstance(props, auth);
        } else {
        	session = Session.getInstance(props);
        }
        
        try {
        	String[] as = toAddr.split(",");
            InternetAddress toAddress[] = new InternetAddress[as.length];
            int ii = 0;
            for(int j = as.length; ii < j; ii++)
            	toAddress[ii] = new InternetAddress(as[ii]);
            MimeMessage msg = new MimeMessage(session);

            msg.setFrom(new InternetAddress(fromAddr, fromName, "utf-8"));
            msg.addRecipients(javax.mail.Message.RecipientType.TO, toAddress);
            msg.setSubject(subject, "utf-8");
            msg.setContent(content, "text/html; charset=utf-8");
            msg.setSentDate(new Date());
            Transport.send(msg);
        } catch (MessagingException mex) {
            log.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) {
                        log.info("    ** Invalid Addresses");

                        if (invalid != null) {
                            for (int i = 0; i < invalid.length; i++)
                            log.info("         " + invalid[i]);
                        }
                    }

                    Address[] validUnsent = sfex.getValidUnsentAddresses();
                    if (validUnsent != null) {
                        log.info("    ** ValidUnsent Addresses");
                        if (validUnsent != null) {
                        for (int i = 0; i < validUnsent.length; i++)
                            log.info("         " + validUnsent[i]);
                        }
                    }

                    Address[] validSent = sfex.getValidSentAddresses();
                    if (validSent != null) {
                        log.info("    ** ValidSent Addresses");
                        if (validSent != null) {
                            for (int i = 0; i < validSent.length; i++)
                                log.info("         " + validSent[i]);
                        }
                    }
                }
                
                if (ex instanceof MessagingException)
                	ex = ((MessagingException) ex).getNextException();
                else ex = null;
            } while (ex != null);
        } catch(UnsupportedEncodingException uee) {
            log.error(uee.getMessage());
        }
    }
                
    public static void runSendMailThread(HashMap hashmap) {
    	(new Thread(new ThreadSendMail(hashmap))).start();
    }
    
    public void run() {
        try {
            sendMailA(ctntHash);
            return;
        } catch(Exception exception) {
            log.error((new StringBuilder(String.valueOf(getClass().getName()))).append(".run()").toString(), exception);
        }
    }
            
    static class MyAuthentication extends Authenticator {
        PasswordAuthentication pa;
        public MyAuthentication(String authId, String AuthPw) {
            //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 = authId;
            String MAIL_AUTH_PW = AuthPw;
            pa = new PasswordAuthentication(MAIL_AUTH_ID, MAIL_AUTH_PW);
            // 여러분들이 사용하고 있는 smtp server의 아이디와 패스워드를 입력한다.
        }          
        // 아래의 메소드는 시스템측에서 사용하는 메소드이다.
        public PasswordAuthentication getPasswordAuthentication() {
        	return pa;
        }
    }
}
728x90