美文网首页
101 Java发送邮件( gmail)

101 Java发送邮件( gmail)

作者: 风之舞者II | 来源:发表于2016-09-23 09:58 被阅读0次

    功能

    提供异步发送邮件功能。

    package org.mall.utils.email;
    
    import java.net.MalformedURLException;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    
    import org.apache.commons.mail.EmailException;
    import org.apache.commons.mail.HtmlEmail;
    import org.apache.log4j.Logger;
    import org.mall.utils.ListUtil;
    import org.mall.utils.PropertiesUtils;
    import org.mall.utils.log.LoggerUtils;
    
    /**
     * @description 邮件发送工具类
     * @author <a href="mailto:fengwuze@kk.com">fengwuze</a>
     * @since 2016年9月20日
     * @version 1.0.0
     */
    public class EmailUtils {
        
        private static Logger logger = Logger.getLogger(EmailUtils.class);
        
        private static ExecutorService exc = new ThreadPoolExecutor(10, 100, 120L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
        
        private static String fromEmail = "kk@gmail.com";
        private static String fromName = "kk";
        
        private static String sendUserName = "fengwuze@kk.com";
        private static String sendPassword = "xxxoooxxxooo";
        
        /**
         * 发送邮件
         * 
         * @param toEmails      收件人列表
         * @param subject       主题
         * @param emailMsg      邮件内容
         */
        public static void sendEmail(String toEmails, String subject, String emailMsg) {
            EmailVo emailVo = new EmailVo();
            emailVo.toEmails = toEmails;
            emailVo.subject = subject;
            emailVo.emailMsg = emailMsg;
            
            sendEmail(new EmailTask(emailVo));
        }
        
        /**
         * 发送邮件(邮件模板)
         * 
         * @param toEmails      收件人列表
         * @param subject       主题
         * @param emailMsg      邮件内容
         */
        public static void sendEmailTemplet(String toEmails, String subject, String templetPath, Map<String, Object> templetParam) {
            EmailVo emailVo = new EmailVo();
            emailVo.toEmails = toEmails;
            emailVo.subject = subject;
            emailVo.emailMsg = EmailTemplateUtils.formatEmailContent(templetPath, templetParam);
            
            sendEmail(new EmailTask(emailVo));
        }
        
        /**
         * 发送邮件
         * 
         * @param emailTask
         */
        public static void sendEmail(EmailTask emailTask) {
            exc.submit(emailTask);
        }
        
        /** 发送邮件Vo */
        static class EmailVo {
            public String toEmails;
            public String subject;
            public String emailMsg;
            public Integer retry = 0;
        }
    
        /** 发送邮件Task */
        public static class EmailTask implements Runnable {
    
            public final EmailVo vo;
            private EmailTask(EmailVo vo) {
                this.vo = vo;
            }
    
            @Override
            public void run() {
                try {
                    HtmlEmail email = new HtmlEmail();
                    email.setCharset("utf-8");
    
                    email.setHostName("smtp.gmail.com");
                    email.setSmtpPort(587);
                    email.setSslSmtpPort("465");
                    email.setSSLOnConnect(true);
    
                    email.setAuthentication(sendUserName, sendPassword);
                    email.setFrom(fromEmail, fromName);
                    email.setSocketConnectionTimeout(10000);
                    email.setSocketTimeout(10000);
    
                    List<String> toEmailList = ListUtil.asList(vo.toEmails, ",");
                    for (String toEmail : toEmailList) {
                        email.addTo(toEmail);
                    }
    
                    email.setSubject(vo.subject);
                    email.setHtmlMsg(vo.emailMsg);
    
                    email.send();
                    LoggerUtils.log(logger, "email send succ, toEmails: %s, subject: %s, emailMsg: %s", vo.toEmails, vo.subject, vo.emailMsg);
                } catch(Exception e) {
                    e.printStackTrace();
                    if(vo != null) {
                        if(vo.retry > 3) {
                            LoggerUtils.log(logger, e, "email send fail, toEmails: %s, subject: %s, emailMsg: %s", vo.toEmails, vo.subject, vo.emailMsg);
                            EmailUtils.sendEmail(new EmailTask(vo));
                        }
                    }
                }
            }
        }
    
        public static void main(String[] args) throws EmailException, MalformedURLException {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("name", "akkiiiii");
            
            EmailUtils.sendEmailTemplet("fengwuze@gmail.com", "HTML格式邮件测试", "/template/mall/welcome.vm", params);
        }
    }
    

    模板工具类

    package org.mall.utils.email;
    
    import java.io.StringWriter;
    import java.util.HashMap;
    import java.util.Map;
    
    import org.apache.velocity.Template;
    import org.apache.velocity.VelocityContext;
    import org.apache.velocity.app.Velocity;
    import org.apache.velocity.app.VelocityEngine;
    
    /**
     * @description 
     * @author <a href="mailto:fengwuze@kk.com">fengwuze</a>
     * @since 2016年9月20日
     * @version 1.0.0
     */
    public class EmailTemplateUtils {
        
        private static VelocityEngine velocityEngine= new VelocityEngine();
        static {
            EmailTemplateUtils.velocityEngine.setProperty(Velocity.RESOURCE_LOADER, "class");
            EmailTemplateUtils.velocityEngine.setProperty("class.resource.loader.class",
                    "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            EmailTemplateUtils.velocityEngine.init();
        }
        
        /**
         * 使用模块技术来生成邮件内容
         * 
         * @param templatePath
         * @param params
         * @return String
         */
        public static String formatEmailContent(String templatePath, Map<String, Object> params) {
            Template t = velocityEngine.getTemplate(templatePath, "UTF-8");
            VelocityContext context = new VelocityContext();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                context.put(entry.getKey(), entry.getValue());
            }
    
            StringWriter writer = new StringWriter();
            t.merge(context, writer);
            
            return writer.toString();
        }
        
        public static void main(String[] args) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("name", "akkiiiii");
            
            for(int i = 0; i < 100000;i++) {
                EmailTemplateUtils.formatEmailContent("/template/mall/welcome.vm", params);
            }
        }
    }

    相关文章

      网友评论

          本文标题:101 Java发送邮件( gmail)

          本文链接:https://www.haomeiwen.com/subject/cortyttx.html