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

  

java HtmlEmail发送邮件工具类的更多相关文章

  1. JAVA发送邮件工具类

    import java.util.Date;import java.util.Properties; import javax.mail.BodyPart;import javax.mail.Mess ...

  2. Jmail发送邮件工具类

    好久没更新博客了,实在是拖延症严重啊,好可怕,先更新个工具类吧,之前写的发送邮件的小工具,话不多说上代码 import lombok.extern.slf4j.Slf4j; import java.u ...

  3. HttpTool.java(在java tool util工具类中已存在) 暂保留

    HttpTool.java 该类为java源生态的http 请求工具,不依赖第三方jar包 ,即插即用. package kingtool; import java.io.BufferedReader ...

  4. java文件处理工具类

    import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedRead ...

  5. java格式处理工具类

    import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOExceptio ...

  6. Java 敏感词过滤,Java 敏感词替换,Java 敏感词工具类

    Java 敏感词过滤,Java 敏感词替换,Java 敏感词工具类   =========================== ©Copyright 蕃薯耀 2017年9月25日 http://www ...

  7. Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类

    Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...

  8. 使用java的Calendar工具类获取到本月的第一天起始时间和最后一天结束时间。

    1.使用java的Calendar工具类获取到本月的第一天起始时间和最后一天结束时间. package com.fline.aic.utils; import java.text.DateFormat ...

  9. JAVA 8 日期工具类

    JAVA 8 日期工具类 主题描述 JAVA中日期时间的历史 代码成果 主题描述 JAVA的日期时间一直比较混乱,本来以为joda会是巅峰,但是JAVA 8改变了我的思想.但是即便在JAVA 8面前, ...

随机推荐

  1. 06.do-while循环的练习

    练习1: namespace _09.do_while循环练习01 { class Program { static void Main(string[] args) { //计算1到100之间的整数 ...

  2. openLayers3 中实现多个Overlay

    此篇的目的是为了记录下用Overlay的一些操作. 其实实现多个就是创建多个div,然后给每个div绑定Overlay. //页面加载完函数 --显示个关键点的名称 window.onload = f ...

  3. redux基本使用

    redux数据流向 基本使用

  4. Celery-------项目目录

    在实际应用中Celery的目录是有规则的 要满足这样的条件才可以 目录Celery_task这个名字可以随意,但是这个目录下一定要有一个celery.py这个文件 from celery import ...

  5. 利用函数回调获取setInterval中返回的值

    我们都知道,定时器里面想返回值如果你用return根本没作用,那么怎么拿到定时器所返回的值呢, 现在只需要利用回调函数,给主函数传一个函数类型的参数callback,然后把想要返回的num再传给cal ...

  6. PLC-Heart

  7. Android 环信(Android)设置头像和昵称的方法

    最近,经常有朋友问到,如何集成环信头像,怎么才能快速显示头像,因时间紧急,很多朋友都没有时间慢慢的研究代码,这里大家稍微花10分钟看一下文章,看完后再花5分钟改一下代码,即可达到你们所要的效果. 当然 ...

  8. 织梦CMS调用文章列表时,怎么显示短时间格式

    问题描述:织梦在上传文章的时候,默认的上传文章的时间格式都是年.月.日.小时.分钟.秒的格式,怎么才能实现仅显示年.月.日的格式呢? 解决方法: [field:pubdate function=&qu ...

  9. ubuntu安装google test

    google test 简称gtest,是一个C/C++的单元测试框架,它的代码在github仓库,使用起来还是挺方便的. 安装 先确保PC上有安装cmake: sudo cmake --versio ...

  10. C语言 条件编译(if )

    #include <stdio.h> #define NUM -1 int main(int argc, const char * argv[]) { #if NUM > 0 pri ...