htmlEmail 发送邮件工具类

发送邮件的依赖:

gradle项目的依赖:

compile('org.apache.commons:commons-email:1.4')

maven项目的依赖:

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-email</artifactId>
   <version>1.4</version>
</dependency>

发送邮件的工具类

package com.cmct.ysq.util;


import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.mail.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @Author Jun
 * @Date 2019/4/28 16:53
 * @Description 发送邮件的工具类
 */
public class SendMailUtil {
    private static final String from = "13*******26@qq.com";
    private static final String fromName = "xxxx";
    private static final String charSet = "utf-8";
    private static final String username = "13******26@qq.com";
    private static final String password = "********";
    private static Logger logger = LoggerFactory.getLogger(SendMailUtil.class);
    private static Map<String, String> hostMap = new HashMap<String, String>();

    static {
        // 126
        hostMap.put("smtp.126", "smtp.126.com");
        // qq
        hostMap.put("smtp.qq", "smtp.qq.com");
        // 163
        hostMap.put("smtp.163", "smtp.163.com");
        // sina
        hostMap.put("smtp.sina", "smtp.sina.com.cn");
        // tom
        hostMap.put("smtp.tom", "smtp.tom.com");
        // 263
        hostMap.put("smtp.263", "smtp.263.net");
        // yahoo
        hostMap.put("smtp.yahoo", "smtp.mail.yahoo.com");
        // hotmail
        hostMap.put("smtp.hotmail", "smtp.live.com");
        // gmail
        hostMap.put("smtp.gmail", "smtp.gmail.com");
        hostMap.put("smtp.port.gmail", "465");
    }

    public static String getHost(String email) throws Exception {
        Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
        Matcher matcher = pattern.matcher(email);
        String key = "unSupportEmail";
        if (matcher.find()) {
            key = "smtp." + matcher.group(1);
        }
        if (hostMap.containsKey(key)) {
            return hostMap.get(key);
        } else {
            throw new Exception("unSupportEmail");
        }
    }

    public static int getSmtpPort(String email) throws Exception {
        Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
        Matcher matcher = pattern.matcher(email);
        String key = "unSupportEmail";
        if (matcher.find()) {
            key = "smtp.port." + matcher.group(1);
        }
        if (hostMap.containsKey(key)) {
            return Integer.parseInt(hostMap.get(key));
        } else {
            return 25;
        }
    }

    /**
     * 发送模板邮件
     *
     * @param toMailAddr   收信人地址
     * @param subject      email主题
     * @param templatePath 模板地址
     * @param map          模板map
     */
    public static void sendFtlMail(String toMailAddr, String subject, String templatePath, Map<String, Object> map) {
        Template template = null;
        Configuration freeMarkerConfig = null;
        HtmlEmail hemail = new HtmlEmail();
        try {
            hemail.setHostName(getHost(from));
            hemail.setSmtpPort(getSmtpPort(from));
            hemail.setCharset(charSet);
            hemail.addTo(toMailAddr);
            hemail.setFrom(from, fromName);
            hemail.setAuthentication(username, password);
            hemail.setSubject(subject);
            freeMarkerConfig = new Configuration();
            freeMarkerConfig.setDirectoryForTemplateLoading(new File(getFilePath()));
            // 获取模板
            template = freeMarkerConfig.getTemplate(getFileName(templatePath), new Locale("Zh_cn"), "UTF-8");
            // 模板内容转换为string
            String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            System.out.println(htmlText);
            hemail.setMsg(htmlText);
            hemail.send();
            System.out.println("email send true!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("email send error!");
        }
    }

    /**
     * 发送普通邮件
     *
     * @param toMailAddr 收信人地址
     * @param subject    email主题
     * @param message    发送email信息
     */
    public static void sendCommonMail(String toMailAddr, String subject, String message, String sendName) {
        HtmlEmail hemail = new HtmlEmail();
        try {
            hemail.setHostName(getHost(from));
            hemail.setSmtpPort(getSmtpPort(from));
            hemail.setCharset(charSet);
            hemail.addTo(toMailAddr);
            hemail.setFrom(from, sendName);
            hemail.setAuthentication(username, password);
            hemail.setSubject(subject);
            hemail.setContent(message, EmailConstants.TEXT_PLAIN);
            hemail.send();
            System.out.println("email send true!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("email send error!");
        }
    }

    public static void sendSimpleTextEmail(String toMailAddr, String subject, String message, String sendName) throws EmailException {
        Email email = new SimpleEmail();
        try {
            email.setHostName(getHost(from));
            email.setSmtpPort(getSmtpPort(from));
            email.setCharset(charSet);
            email.setAuthentication(username, password);
            email.setSSLOnConnect(true);
            email.setFrom(from, sendName, charSet);
            email.setSubject(subject);
            email.setMsg(message);
            email.addTo(toMailAddr);
            email.send();
            System.out.println("email send true!");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("email send error!");
        }
    }

    /**
     * 功能描述:发送带多个附件的邮件
     *
     * @param emailAttachments 附件内容对象 多个
     * @param toMailAddr       收信人地址
     * @param subject          email主题
     * @param message          发送email信息
     */
    public static void sendEnclosureMail(List<EmailAttachment> emailAttachments,
                                         String toMailAddr,
                                         String subject,
                                         String message,
                                         String sendPersonName) {
        try {
            HtmlEmail hemail = new HtmlEmail();
            hemail.setHostName(getHost(from));
            hemail.setSmtpPort(getSmtpPort(from));
            hemail.setCharset(charSet);
            hemail.addTo(toMailAddr);
            hemail.setFrom(from, sendPersonName);
            hemail.setAuthentication(username, password);
            hemail.setSubject(subject);
            hemail.setMsg(message);
            for (EmailAttachment emailAttachment : emailAttachments) {
                hemail.attach(emailAttachment);
            }
            hemail.send();
            System.out.println("email send true!");
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("---------发往" + toMailAddr + "的邮件出现异常--------");
            System.out.println("email send error!");
        }
    }

    /**
     * @param emailAttachments
     * @param mailModel
     * @return
     */
    public static void sendEnclosureMails(List<EmailAttachment> emailAttachments,
                                          MailModelObject mailModel) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("subject", "测试标题");
            map.put("content", "测试内容");
            System.out.println("接收人邮箱: " + mailModel.getReceiveEmail());
            System.out.println("邮箱正文::" + mailModel.getMailText());
            System.out.println("发送人 :" + mailModel.getSendProson());
            System.out.println(mailModel.getSendProson().length());
            System.out.println("邮箱主题:" + mailModel.getTheme());
            final String mail = mailModel.getSendProson();
            HtmlEmail hemail = new HtmlEmail();
            hemail.setHostName(getHost(from));
            //设定的发送邮件服务器的主机名
            hemail.setSmtpPort(getSmtpPort(from));
            //设置传出邮件服务器的端口号
            hemail.setCharset("utf-8");
            //设置消息字符集 , 注意设置之前添加消息内容
            hemail.addTo(mailModel.getReceiveEmail());
            //设置发送人
            hemail.setFrom(from, mailModel.getSendProson());
            hemail.setAuthentication(username, password);
            hemail.setSubject(mailModel.getTheme());
            hemail.setMsg(mailModel.getMailText());
             /*
             hemail.setSubject("zheshi zhuti");
             hemail.setMsg("weadsdasdas");
             */
            for (EmailAttachment emailAttachment : emailAttachments) {
                hemail.attach(emailAttachment);
            }
            hemail.send();
            System.out.println("email send true!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("email send error!");
        }
    }

    /**
     * 发送发送带html的邮件
     *
     * @param toMailAddr 收信人地址
     * @param subject    email主题
     * @param message    发送带html的email信息
     */
    public static boolean sendHTMLMail(String toMailAddr,
                                       String subject,
                                       String message,
                                       String sendName) {
        boolean flag = true;
        //发送成功与失败的标识
        try {
            HtmlEmail hemail = new HtmlEmail();
            hemail.setHostName(getHost(from));
            hemail.setSmtpPort(getSmtpPort(from));
            hemail.setCharset(charSet);
            hemail.addTo(toMailAddr);
            hemail.setFrom(from, sendName);
            hemail.setAuthentication(username, password);
            hemail.setSubject(subject);
            hemail.setContent(message, EmailConstants.TEXT_HTML);
            hemail.send();
            hemail.setHtmlMsg(message);
            System.out.println("email send true!");
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
            logger.info("---------发往" + toMailAddr + "的邮件出现异常--------");
            System.out.println("email-html send error!");
        }
        return flag;
    }

    public static String getHtmlText(String templatePath, Map<String, Object> map) {
        Template template = null;
        String htmlText = "";
        try {
            Configuration freeMarkerConfig = null;
            freeMarkerConfig = new Configuration();
            freeMarkerConfig.setDirectoryForTemplateLoading(new File(getFilePath()));
            // 获取模板
            template = freeMarkerConfig.getTemplate(getFileName(templatePath), new Locale("Zh_cn"), "UTF-8");
            // 模板内容转换为string
            htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            System.out.println(htmlText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return htmlText;
    }

    private static String getFilePath() {
        String path = getAppPath(SendMailUtil.class);
        path = path + File.separator + "mailtemplate" + File.separator;
        path = path.replace("\\", "/");
        System.out.println(path);
        return path;
    }

    private static String getFileName(String path) {
        path = path.replace("\\", "/");
        System.out.println(path);
        return path.substring(path.lastIndexOf("/") + 1);
    }

    // @SuppressWarnings("unchecked")
    public static String getAppPath(Class<?> cls) {
        // 检查用户传入的参数是否为空
        if (cls == null) throw new IllegalArgumentException("参数不能为空!");
        ClassLoader loader = cls.getClassLoader();
        // 获得类的全名,包括包名
        String clsName = cls.getName() + ".class";
        // 获得传入参数所在的包
        Package pack = cls.getPackage();
        String path = "";
        // 如果不是匿名包,将包名转化为路径
        if (pack != null) {
            String packName = pack.getName();
            // 此处简单判定是否是Java基础类库,防止用户传入JDK内置的类库
            if (packName.startsWith("java.") || packName.startsWith("javax."))
                throw new IllegalArgumentException("不要传送系统类!");
            // 在类的名称中,去掉包名的部分,获得类的文件名
            clsName = clsName.substring(packName.length() + 1);
            // 判定包名是否是简单包名,如果是,则直接将包名转换为路径,
            if (packName.indexOf(".") < 0)
                path = packName + "/";
            else {
                // 否则按照包名的组成部分,将包名转换为路径
                int start = 0, end = 0;
                end = packName.indexOf(".");
                while (end != -1) {
                    path = path + packName.substring(start, end) + "/";
                    start = end + 1;
                    end = packName.indexOf(".", start);
                }
                path = path + packName.substring(start) + "/";
            }
        }
        // 调用ClassLoader的getResource方法,传入包含路径信息的类文件名
        java.net.URL url = loader.getResource(path + clsName);
        // 从URL对象中获取路径信息
        String realPath = url.getPath();
        // 去掉路径信息中的协议名"file:"
        int pos = realPath.indexOf("file:");
        if (pos > -1) realPath = realPath.substring(pos + 5);
        // 去掉路径信息最后包含类文件信息的部分,得到类所在的路径
        pos = realPath.indexOf(path + clsName);
        realPath = realPath.substring(0, pos - 1);
        // 如果类文件被打包到JAR等文件中时,去掉对应的JAR等打包文件名
        if (realPath.endsWith("!")) realPath = realPath.substring(0, realPath.lastIndexOf("/"));
        /*------------------------------------------------------------
        ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径 中存在中文和空格时,
        他会对这些字符进行转换,这样,得到的往往不是我们想要 的真实路径,在此,
        调用了URLDecoder的decode方法进行解码,以便得到原始的 中文及空格路径
        -------------------------------------------------------------*/
        try {
            realPath = java.net.URLDecoder.decode(realPath, "utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("realPath----->" + realPath);
        return realPath;
    }
}

发送邮件需要依赖的类

package com.cmct.ysq.util;

/**
 * @Author Jun
 * @Date 2019/4/29 9:26
 * @Description TODO
 */
public class MailModelObject {
    private String receiveEmail;
    private String mailText;
    private String sendProson;
    private String theme;

    public String getReceiveEmail() {
        return receiveEmail;
    }

    public void setReceiveEmail(String receiveEmail) {
        this.receiveEmail = receiveEmail;
    }

    public String getMailText() {
        return mailText;
    }

    public void setMailText(String mailText) {
        this.mailText = mailText;
    }

    public String getSendProson() {
        return sendProson;
    }

    public void setSendProson(String sendProson) {
        this.sendProson = sendProson;
    }

    public String getTheme() {
        return theme;
    }

    public void setTheme(String theme) {
        this.theme = theme;
    }
}

以上工具类转自:https://blog.csdn.net/liu_yulong/article/details/83022835

//初始化邮件 void InitEmail(C01waSendMail* m_globalEmail,String sendermail,String sender,String senderpwd,String srv,int port = 25,bool bSsl = false) { m_globalEmail->m_Auth = CPJNSMTPConnection::AuthenticationMethod::AUTH_AUTO; m_globalEmail->m_bAutoDial = true; m_globalEmail->m_bSSL = bSsl; m_globalEmail->m_sUsername = sender.c_str(); m_globalEmail->m_sAddress = sendermail.c_str(); m_globalEmail->m_sPassword = senderpwd.c_str(); m_globalEmail->m_sHost = srv.c_str(); m_globalEmail->m_nPort = port; m_globalEmail->m_sEncodingFriendly = _T("Chinese Simplified (GB2312)"); m_globalEmail->m_sEncodingCharset = _T("gb2312"); m_globalEmail->m_bMime = 1; m_globalEmail->m_bHTML = 1; m_globalEmail->m_Priority = CPJNSMTPMessage::PRIORITY::NormalPriority; m_globalEmail->m_bDSN = FALSE; m_globalEmail->m_bDSNSuccess = FALSE; m_globalEmail->m_bDSNFailure = FALSE; m_globalEmail->m_bDSNDelay = FALSE; m_globalEmail->m_bDSNHeaders = FALSE; m_globalEmail->m_bDNSLookup = FALSE; } //发送邮件 void SendEmail(const char* recvemail,const char* subject,const char* body,const char * sCC=NULL,const char * bCC = NULL,const char * attach = NULL) { //初始化邮箱 //注意释放内存 C01waSendMail *m_globalEmail = new C01waSendMail; if(strlen(m_con1.m_eamil)>0&&strlen(m_con1.m_pwd)&&strlen(m_con1.m_smtpsrv)&&m_con1.port>0) { char * p = strdup(m_con1.m_eamil); char * pp = strstr(p,"@"); if(pp>0) pp[0] = '\0'; InitEmail(m_globalEmail,m_con1.m_eamil,p,m_con1.m_pwd,m_con1.m_smtpsrv,m_con1.port,m_con1.ssl); free(p); if(subject>0) m_globalEmail->m_sSubject.Format("%s",subject); if(sCC>0) m_globalEmail->m_sCC.Format("%s",sCC); if(bCC>0) m_globalEmail->m_sBCC.Format("%s",bCC); if(body>0) m_globalEmail->m_sBody.Format("%s",body); if(attach>0) m_globalEmail->m_sFile.Format("%s",attach); if(recvemail>0) m_globalEmail->m_sTo.Format("%s",recvemail); m_globalEmail->SendEmail(); } }
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页