zoukankan      html  css  js  c++  java
  • Java 实现 HtmlEmail 邮件发送功能

    引言

         在平常的企业级应用开发过程中,可能会涉及到一些资讯通知需要传达,以及软件使用过程中有一些安全性的东西需要及早知道和了解,这时候在局域网之间就可以通过发送邮件的方式了。以下就是代码实现了: 

      1 package com.sh.xrsite.common.utils;
      2  
      3 import java.io.File;
      4 import java.util.HashMap;
      5 import java.util.Locale;
      6 import java.util.Map;
      7 import java.util.regex.Matcher;
      8 import java.util.regex.Pattern;
      9  
     10 import org.apache.commons.mail.HtmlEmail;
     11 import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
     12  
     13 import freemarker.template.Configuration;
     14 import freemarker.template.Template;
     15  
     16 /**
     17  * 发送电子邮件
     18  */
     19 public class SendMailUtil {
     20  
     21     private static final String from = "zsq@163.com";
     22     private static final String fromName = "测试公司";
     23     private static final String charSet = "utf-8";
     24     private static final String username = "zsq@163.com";
     25     private static final String password = "123456";
     26  
     27     private static Map<String, String> hostMap = new HashMap<String, String>();
     28     static {
     29         // 126
     30         hostMap.put("smtp.126", "smtp.126.com");
     31         // qq
     32         hostMap.put("smtp.qq", "smtp.qq.com");
     33  
     34         // 163
     35         hostMap.put("smtp.163", "smtp.163.com");
     36  
     37         // sina
     38         hostMap.put("smtp.sina", "smtp.sina.com.cn");
     39  
     40         // tom
     41         hostMap.put("smtp.tom", "smtp.tom.com");
     42  
     43         // 263
     44         hostMap.put("smtp.263", "smtp.263.net");
     45  
     46         // yahoo
     47         hostMap.put("smtp.yahoo", "smtp.mail.yahoo.com");
     48  
     49         // hotmail
     50         hostMap.put("smtp.hotmail", "smtp.live.com");
     51  
     52         // gmail
     53         hostMap.put("smtp.gmail", "smtp.gmail.com");
     54         hostMap.put("smtp.port.gmail", "465");
     55     }
     56  
     57     public static String getHost(String email) throws Exception {
     58         Pattern pattern = Pattern.compile("\w+@(\w+)(\.\w+){1,2}");
     59         Matcher matcher = pattern.matcher(email);
     60         String key = "unSupportEmail";
     61         if (matcher.find()) {
     62             key = "smtp." + matcher.group(1);
     63         }
     64         if (hostMap.containsKey(key)) {
     65             return hostMap.get(key);
     66         } else {
     67             throw new Exception("unSupportEmail");
     68         }
     69     }
     70  
     71     public static int getSmtpPort(String email) throws Exception {
     72         Pattern pattern = Pattern.compile("\w+@(\w+)(\.\w+){1,2}");
     73         Matcher matcher = pattern.matcher(email);
     74         String key = "unSupportEmail";
     75         if (matcher.find()) {
     76             key = "smtp.port." + matcher.group(1);
     77         }
     78         if (hostMap.containsKey(key)) {
     79             return Integer.parseInt(hostMap.get(key));
     80         } else {
     81             return 25;
     82         }
     83     }
     84  
     85     /**
     86      * 发送模板邮件
     87      *
     88      * @param toMailAddr
     89      *            收信人地址
     90      * @param subject
     91      *            email主题
     92      * @param templatePath
     93      *            模板地址
     94      * @param map
     95      *            模板map
     96      */
     97     public static void sendFtlMail(String toMailAddr, String subject,
     98             String templatePath, Map<String, Object> map) {
     99         Template template = null;
    100         Configuration freeMarkerConfig = null;
    101         HtmlEmail hemail = new HtmlEmail();
    102         try {
    103             hemail.setHostName(getHost(from));
    104             hemail.setSmtpPort(getSmtpPort(from));
    105             hemail.setCharset(charSet);
    106             hemail.addTo(toMailAddr);
    107             hemail.setFrom(from, fromName);
    108             hemail.setAuthentication(username, password);
    109             hemail.setSubject(subject);
    110             freeMarkerConfig = new Configuration();
    111             freeMarkerConfig.setDirectoryForTemplateLoading(new File(
    112                     getFilePath()));
    113             // 获取模板
    114             template = freeMarkerConfig.getTemplate(getFileName(templatePath),
    115                     new Locale("Zh_cn"), "UTF-8");
    116             // 模板内容转换为string
    117             String htmlText = FreeMarkerTemplateUtils
    118                     .processTemplateIntoString(template, map);
    119             System.out.println(htmlText);
    120             hemail.setMsg(htmlText);
    121             hemail.send();
    122             System.out.println("email send true!");
    123         } catch (Exception e) {
    124             e.printStackTrace();
    125             System.out.println("email send error!");
    126         }
    127     }
    128  
    129     /**
    130      * 发送普通邮件
    131      *
    132      * @param toMailAddr
    133      *            收信人地址
    134      * @param subject
    135      *            email主题
    136      * @param message
    137      *            发送email信息
    138      */
    139     public static void sendCommonMail(String toMailAddr, String subject,
    140             String message) {
    141         HtmlEmail hemail = new HtmlEmail();
    142         try {
    143             hemail.setHostName(getHost(from));
    144             hemail.setSmtpPort(getSmtpPort(from));
    145             hemail.setCharset(charSet);
    146             hemail.addTo(toMailAddr);
    147             hemail.setFrom(from, fromName);
    148             hemail.setAuthentication(username, password);
    149             hemail.setSubject(subject);
    150             hemail.setMsg(message);
    151             hemail.send();
    152             System.out.println("email send true!");
    153         } catch (Exception e) {
    154             e.printStackTrace();
    155             System.out.println("email send error!");
    156         }
    157  
    158     }
    159 
    160     
    161      /**
    162      * 发送普通邮件
    163      * @param hostIp    邮件服务器地址
    164      * @param sendMailAddr  发送发邮箱地址
    165      * @param sendUserName 发送方姓名
    166      * @param username  邮箱用户名
    167      * @param password  邮箱密码
    168      * @param  toMailAddr  收信人邮箱地址                 
    169      * @param  subject  email主题
    170      * @param  message  发送email信息         
    171      */
    172     public static boolean sendCommonMail(String hostIp, String sendMailAddr, String sendUserName, String username, String password,String toMailAddr, String subject,
    173             String message) {
    174         HtmlEmail hemail = new HtmlEmail();
    175         boolean flag;
    176         try {
    177           
    178             hemail.setHostName(hostIp);
    179             hemail.setSmtpPort(getSmtpPort(sendMailAddr));
    180             hemail.setCharset(charSet);
    181             hemail.addTo(toMailAddr);
    182             hemail.setFrom(sendMailAddr, sendUserName);
    183             hemail.setAuthentication(username, password);
    184             hemail.setSubject(subject);
    185             hemail.setMsg(message);
    186             hemail.send();
    187             flag=true;
    188             System.out.println("email send true!");
    189           
    190         } catch (Exception e) {
    191             e.printStackTrace();
    192             flag=false;
    193             System.out.println("email send error!");
    194         }
    195         
    196        return flag;
    197     }
    198  
    199     
    200  
    201     public static String getHtmlText(String templatePath,
    202             Map<String, Object> map) {
    203         Template template = null;
    204         String htmlText = "";
    205         try {
    206             Configuration freeMarkerConfig = null;
    207             freeMarkerConfig = new Configuration();
    208             freeMarkerConfig.setDirectoryForTemplateLoading(new File(
    209                     getFilePath()));
    210             // 获取模板
    211             template = freeMarkerConfig.getTemplate(getFileName(templatePath),
    212                     new Locale("Zh_cn"), "UTF-8");
    213             // 模板内容转换为string
    214             htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(
    215                     template, map);
    216             System.out.println(htmlText);
    217         } catch (Exception e) {
    218             e.printStackTrace();
    219         }
    220         return htmlText;
    221     }
    222  
    223     private static String getFilePath() {
    224         String path = getAppPath(SendMailUtil.class);
    225         path = path + File.separator + "mailtemplate" + File.separator;
    226         path = path.replace("\", "/");
    227         System.out.println(path);
    228         return path;
    229     }
    230  
    231     private static String getFileName(String path) {
    232         path = path.replace("\", "/");
    233         System.out.println(path);
    234         return path.substring(path.lastIndexOf("/") + 1);
    235     }
    236  
    237     // @SuppressWarnings("unchecked")
    238     public static String getAppPath(Class<?> cls) {
    239         // 检查用户传入的参数是否为空
    240         if (cls == null)
    241             throw new java.lang.IllegalArgumentException("参数不能为空!");
    242         ClassLoader loader = cls.getClassLoader();
    243         // 获得类的全名,包括包名
    244         String clsName = cls.getName() + ".class";
    245         // 获得传入参数所在的包
    246         Package pack = cls.getPackage();
    247         String path = "";
    248         // 如果不是匿名包,将包名转化为路径
    249         if (pack != null) {
    250             String packName = pack.getName();
    251             // 此处简单判定是否是Java基础类库,防止用户传入JDK内置的类库
    252             if (packName.startsWith("java.") || packName.startsWith("javax."))
    253                 throw new java.lang.IllegalArgumentException("不要传送系统类!");
    254             // 在类的名称中,去掉包名的部分,获得类的文件名
    255             clsName = clsName.substring(packName.length() + 1);
    256             // 判定包名是否是简单包名,如果是,则直接将包名转换为路径,
    257             if (packName.indexOf(".") < 0)
    258                 path = packName + "/";
    259             else {// 否则按照包名的组成部分,将包名转换为路径
    260                 int start = 0, end = 0;
    261                 end = packName.indexOf(".");
    262                 while (end != -1) {
    263                     path = path + packName.substring(start, end) + "/";
    264                     start = end + 1;
    265                     end = packName.indexOf(".", start);
    266                 }
    267                 path = path + packName.substring(start) + "/";
    268             }
    269         }
    270         // 调用ClassLoader的getResource方法,传入包含路径信息的类文件名
    271         java.net.URL url = loader.getResource(path + clsName);
    272         // 从URL对象中获取路径信息
    273         String realPath = url.getPath();
    274         // 去掉路径信息中的协议名"file:"
    275         int pos = realPath.indexOf("file:");
    276         if (pos > -1)
    277             realPath = realPath.substring(pos + 5);
    278         // 去掉路径信息最后包含类文件信息的部分,得到类所在的路径
    279         pos = realPath.indexOf(path + clsName);
    280         realPath = realPath.substring(0, pos - 1);
    281         // 如果类文件被打包到JAR等文件中时,去掉对应的JAR等打包文件名
    282         if (realPath.endsWith("!"))
    283             realPath = realPath.substring(0, realPath.lastIndexOf("/"));
    284         /*------------------------------------------------------------
    285          ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径
    286           中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要
    287           的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的
    288           中文及空格路径
    289         -------------------------------------------------------------*/
    290         try {
    291             realPath = java.net.URLDecoder.decode(realPath, "utf-8");
    292         } catch (Exception e) {
    293             throw new RuntimeException(e);
    294         }
    295         System.out.println("realPath----->" + realPath);
    296         return realPath;
    297     }
    298  
    299     // private static File getFile(String path){
    300     // File file =
    301     // SendMail.class.getClassLoader().getResource("mailtemplate/test.ftl").getFile();
    302     // return file;
    303     // }
    304     //
    305  
    306     public static void main(String[] args) {
    307          HtmlEmail hemail = new HtmlEmail();
    308          try {
    309          hemail.setHostName("smtp.163.com");
    310          hemail.setCharset("utf-8");
    311          hemail.addTo("收件邮箱地址");
    312          hemail.setFrom("发件邮箱地铁", "网易");
    313          hemail.setAuthentication("wang_yi@163.com", "发件邮箱密码");
    314          hemail.setSubject("sendemail test!");
    315          hemail.setMsg("<a href="http://www.google.cn">谷歌</a><br/>");
    316          hemail.send();
    317          System.out.println("email send true!");
    318          } catch (Exception e) {
    319          e.printStackTrace();
    320          System.out.println("email send error!");
    321          }
    322 //        Map<String, Object> map = new HashMap<String, Object>();
    323 //        map.put("subject", "测试标题");
    324 //        map.put("content", "测试 内容");
    325 //        String templatePath = "mailtemplate/test.ftl";
    326 //        sendFtlMail("test@163.com", "sendemail test!", templatePath, map);
    327  
    328         // System.out.println(getFileName("mailtemplate/test.ftl"));
    329     }
    330  
    331 }

        注意:要想发送邮件还必须在服务器上创建一个邮件服务器和本地安装接收邮件客户端 (FoxmailSetup.exe + hMailServer.exe)!

        具体的安装和配置参考https://www.cnblogs.com/zhaosq/p/11088787.html

  • 相关阅读:
    linux常用的命令
    针对无线信道衰落特性分析3G,4G,5G的关键技术异同点
    re-id 资料集
    kissme
    数据集
    matlab print,disp,fprint,fscan
    PCA样本数量少于矩阵维数
    pca降维详细过程
    TOJ 1856 Is It A Tree?
    POJ 2570 Fiber Network
  • 原文地址:https://www.cnblogs.com/zhaosq/p/11088586.html
Copyright © 2011-2022 走看看