Java項目 郵件發送工具類

 
package com.litchi.common.utils;

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;

import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailConstants;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.SimpleEmail;
import org.apache.fop.fonts.base14.Helvetica;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import com.thinkgem.jeesite.modules.oem.entity.mailModelObject.MailModelObject;
import com.thinkgem.jeesite.modules.oem.web.apply.OemIssueApplyController;
import com.thinkgem.jeesite.modules.sys.utils.MailModel;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 發送電子郵件
 */
public class SendMailUtil {
 
    private static final String from = "[email protected]";
    private static final String fromName = "XXX";
    private static final String charSet = "utf-8";
    private static final String username = "[email protected]";
    private static final String password = "xxx";
    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.setMsg(message);
            //hemail.set
            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 java.lang.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 java.lang.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;
    }


    public static void main(String[] args) {
        // HtmlEmail hemail = new HtmlEmail();
        // try {
        // hemail.setHostName("smtp.exmail.qq.com");
        // hemail.setCharset("utf-8");
        // hemail.addTo("[email protected]");
        // hemail.setFrom("[email protected]", "xxx");
        // hemail.setAuthentication("[email protected]", "dd@aa");
        // hemail.setSubject("sendemail test!");
        // hemail.setMsg("<a href=\"http://www.google.cn\">baidu</a><br/>");
        // hemail.send();
        // System.out.println("email send true!");
        // } catch (Exception e) {
        // e.printStackTrace();
        // System.out.println("email send error!");
        // }
    }


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章