引言

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

  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. //
  30. hostMap.put("smtp.126", "smtp.126.com");
  31. // qq
  32. hostMap.put("smtp.qq", "smtp.qq.com");
  33.  
  34. //
  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. //
  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. * @param hostIp 邮件服务器地址
  163. * @param sendMailAddr 发送发邮箱地址
  164. * @param sendUserName 发送方姓名
  165. * @param username 邮箱用户名
  166. * @param password 邮箱密码
  167. * @param toMailAddr 收信人邮箱地址
  168. * @param subject email主题
  169. * @param message 发送email信息
  170. */
  171. public static boolean sendCommonMail(String hostIp, String sendMailAddr, String sendUserName, String username, String password,String toMailAddr, String subject,
  172. String message) {
  173. HtmlEmail hemail = new HtmlEmail();
  174. boolean flag;
  175. try {
  176.  
  177. hemail.setHostName(hostIp);
  178. hemail.setSmtpPort(getSmtpPort(sendMailAddr));
  179. hemail.setCharset(charSet);
  180. hemail.addTo(toMailAddr);
  181. hemail.setFrom(sendMailAddr, sendUserName);
  182. hemail.setAuthentication(username, password);
  183. hemail.setSubject(subject);
  184. hemail.setMsg(message);
  185. hemail.send();
  186. flag=true;
  187. System.out.println("email send true!");
  188.  
  189. } catch (Exception e) {
  190. e.printStackTrace();
  191. flag=false;
  192. System.out.println("email send error!");
  193. }
  194.  
  195. return flag;
  196. }
  197.  
  198. public static String getHtmlText(String templatePath,
  199. Map<String, Object> map) {
  200. Template template = null;
  201. String htmlText = "";
  202. try {
  203. Configuration freeMarkerConfig = null;
  204. freeMarkerConfig = new Configuration();
  205. freeMarkerConfig.setDirectoryForTemplateLoading(new File(
  206. getFilePath()));
  207. // 获取模板
  208. template = freeMarkerConfig.getTemplate(getFileName(templatePath),
  209. new Locale("Zh_cn"), "UTF-8");
  210. // 模板内容转换为string
  211. htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(
  212. template, map);
  213. System.out.println(htmlText);
  214. } catch (Exception e) {
  215. e.printStackTrace();
  216. }
  217. return htmlText;
  218. }
  219.  
  220. private static String getFilePath() {
  221. String path = getAppPath(SendMailUtil.class);
  222. path = path + File.separator + "mailtemplate" + File.separator;
  223. path = path.replace("\\", "/");
  224. System.out.println(path);
  225. return path;
  226. }
  227.  
  228. private static String getFileName(String path) {
  229. path = path.replace("\\", "/");
  230. System.out.println(path);
  231. return path.substring(path.lastIndexOf("/") + 1);
  232. }
  233.  
  234. // @SuppressWarnings("unchecked")
  235. public static String getAppPath(Class<?> cls) {
  236. // 检查用户传入的参数是否为空
  237. if (cls == null)
  238. throw new java.lang.IllegalArgumentException("参数不能为空!");
  239. ClassLoader loader = cls.getClassLoader();
  240. // 获得类的全名,包括包名
  241. String clsName = cls.getName() + ".class";
  242. // 获得传入参数所在的包
  243. Package pack = cls.getPackage();
  244. String path = "";
  245. // 如果不是匿名包,将包名转化为路径
  246. if (pack != null) {
  247. String packName = pack.getName();
  248. // 此处简单判定是否是Java基础类库,防止用户传入JDK内置的类库
  249. if (packName.startsWith("java.") || packName.startsWith("javax."))
  250. throw new java.lang.IllegalArgumentException("不要传送系统类!");
  251. // 在类的名称中,去掉包名的部分,获得类的文件名
  252. clsName = clsName.substring(packName.length() + 1);
  253. // 判定包名是否是简单包名,如果是,则直接将包名转换为路径,
  254. if (packName.indexOf(".") < 0)
  255. path = packName + "/";
  256. else {// 否则按照包名的组成部分,将包名转换为路径
  257. int start = 0, end = 0;
  258. end = packName.indexOf(".");
  259. while (end != -1) {
  260. path = path + packName.substring(start, end) + "/";
  261. start = end + 1;
  262. end = packName.indexOf(".", start);
  263. }
  264. path = path + packName.substring(start) + "/";
  265. }
  266. }
  267. // 调用ClassLoader的getResource方法,传入包含路径信息的类文件名
  268. java.net.URL url = loader.getResource(path + clsName);
  269. // 从URL对象中获取路径信息
  270. String realPath = url.getPath();
  271. // 去掉路径信息中的协议名"file:"
  272. int pos = realPath.indexOf("file:");
  273. if (pos > -1)
  274. realPath = realPath.substring(pos + 5);
  275. // 去掉路径信息最后包含类文件信息的部分,得到类所在的路径
  276. pos = realPath.indexOf(path + clsName);
  277. realPath = realPath.substring(0, pos - 1);
  278. // 如果类文件被打包到JAR等文件中时,去掉对应的JAR等打包文件名
  279. if (realPath.endsWith("!"))
  280. realPath = realPath.substring(0, realPath.lastIndexOf("/"));
  281. /*------------------------------------------------------------
  282. ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径
  283. 中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要
  284. 的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的
  285. 中文及空格路径
  286. -------------------------------------------------------------*/
  287. try {
  288. realPath = java.net.URLDecoder.decode(realPath, "utf-8");
  289. } catch (Exception e) {
  290. throw new RuntimeException(e);
  291. }
  292. System.out.println("realPath----->" + realPath);
  293. return realPath;
  294. }
  295.  
  296. // private static File getFile(String path){
  297. // File file =
  298. // SendMail.class.getClassLoader().getResource("mailtemplate/test.ftl").getFile();
  299. // return file;
  300. // }
  301. //
  302.  
  303. public static void main(String[] args) {
  304. HtmlEmail hemail = new HtmlEmail();
  305. try {
  306. hemail.setHostName("smtp.163.com");
  307. hemail.setCharset("utf-8");
  308. hemail.addTo("收件邮箱地址");
  309. hemail.setFrom("发件邮箱地铁", "网易");
  310. hemail.setAuthentication("wang_yi@163.com", "发件邮箱密码");
  311. hemail.setSubject("sendemail test!");
  312. hemail.setMsg("<a href=\"http://www.google.cn\">谷歌</a><br/>");
  313. hemail.send();
  314. System.out.println("email send true!");
  315. } catch (Exception e) {
  316. e.printStackTrace();
  317. System.out.println("email send error!");
  318. }
  319. // Map<String, Object> map = new HashMap<String, Object>();
  320. // map.put("subject", "测试标题");
  321. // map.put("content", "测试 内容");
  322. // String templatePath = "mailtemplate/test.ftl";
  323. // sendFtlMail("test@163.com", "sendemail test!", templatePath, map);
  324.  
  325. // System.out.println(getFileName("mailtemplate/test.ftl"));
  326. }
  327.  
  328. }

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

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

Java 实现 HtmlEmail 邮件发送功能的更多相关文章

  1. SpringBoot 2.X从0到1实现邮件发送功能

    Spring中提供了JavaMailSender接口实现邮件发送功能,在SpringBoot2.X中也封装了发送邮件相关的Starter并且提供了自动化配置. 本文目录 一.添加对应的Starter二 ...

  2. spring-boot-route(二十二)实现邮件发送功能

    在项目开发中,除了需要短信验证外,有时候为了节省 短信费也会使用邮件发送.在Spring项目中发送邮件需要封装复杂的消息体,不太方便.而在Spring Boot项目中发送邮件就太简单了,下面一起来看看 ...

  3. .NET开发邮件发送功能的全面教程(含邮件组件源码)

    今天,给大家分享的是如何在.NET平台中开发“邮件发送”功能.在网上搜的到的各种资料一般都介绍的比较简单,那今天我想比较细的整理介绍下: 1)         邮件基础理论知识 2)         ...

  4. 用ASP.NET Core 1.0中实现邮件发送功能-阿里云邮件推送篇

    在上篇中用MailKit实现了Asp.net core 邮件发送功能,但一直未解决阿里云邮件推送问题,提交工单一开始的回复不尽如人意,比如您的网络问题,您的用户名密码不正确等,但继续沟通下阿里云客户还 ...

  5. redmine邮件发送功能配置详解

    redmine的邮件发送功能还是很有用的.像项目有更新啦,任务分配啦,都能邮件发送的相关责任人.我自己在linux服务器上安装并启动了redmine后,邮件一直发送了不了.查了网上的资料,都是讲修改下 ...

  6. .NET开发邮件发送功能

    .NET开发邮件发送功能 今天,给大家分享的是如何在.NET平台中开发“邮件发送”功能.在网上搜的到的各种资料一般都介绍的比较简单,那今天我想比较细的整理介绍下: 1)         邮件基础理论知 ...

  7. shell邮件发送功能实现

    本文中以163邮箱为例,测试shell邮件发送功能.常见的工具有:mailx.sendmail.mutt等. 1.设置邮件客户端 (1)启用pop3.smtp服务,以支持第三方客户端支持 (2)设置授 ...

  8. Spring进阶—如何用Java代码实现邮件发送(一)

    相关文章: <Spring进阶—如何用Java代码实现邮件发送(二)> 在一些项目里面如进销存系统,对一些库存不足发出预警提示消息,招聘网站注册用户验证email地址等都需要用到邮件发送技 ...

  9. System.Net邮件发送功能踩过的坑

    System.Net邮件发送功能踩过的坑 目录 System.Net邮件发送功能踩过的坑 1.EazyEmail邮件发送类库 2.邮件发送授权码与邮件密码 3.通过邮件密码来发送邮件 4.Wiresh ...

随机推荐

  1. JS数组去除空值

    /** * 扩展Array方法, 去除数组中空白数据 */ Array.prototype.notempty = function() { var arr = []; this.map(functio ...

  2. 关于Excel做表小知识记录

    关于Excel做表小知识记录 最近使用Excel做了一系列的报表,觉得这是个很神奇的东西哈哈哈,以前我可是一想到Excel就开始头疼的人...  能用代码或者SQL语句解决的问题绝不会愿意留在Exce ...

  3. 易优CMS:channel的基础用法

    [基础用法] 名称:channel 功能:易优常用标记,可以循环嵌套标签.通常用于网站导航以获取站点栏目信息,方便网站会员分类浏览整站信息 语法: {eyou:channel type='top' r ...

  4. vue 客户端渲染和服务端渲染

    参考链接 https://www.cnblogs.com/tiedaweishao/p/6644267.html

  5. Linux下Mysql安装教程详解

    Linux下软件安装一般有三种方式:RPM包方式(通过Redhat 第三方包管理系统).二进制包和源码包.本篇主要介绍二进制包安装mysql数据库的方式. 如何获取二进制源码包 当然是到mysql官网 ...

  6. jwt认证生成后的token后端解析

    一.首先前端发送token token所在的位置headers {'authorization':token的值',Content-Type':application/json} 在ajax写 //只 ...

  7. Customize the View Items Layout 自定义视图项目布局

    In this lesson, you will learn how to customize the default editor layout in a Detail View. For this ...

  8. BASE64Encoder cannot be resolved to a type类似问题的解决办法

    我们有时候会碰见在JDK或者其他jar包中提供了某方法或者类,接口,而开发工具仍然报红,无法使用该类或者方法,那是应为我们的编译器没有识别,或者没有支持某些方法或者类 这个时候需要我们手动的开启.具体 ...

  9. Bootstrap 时间日历插件bootstrap-datetimepicker配置与应用小结

    Bootstrap时间日历插件bootstrap-datetimepicker配置与应用小结   by:授客 QQ:1033553122 1.   测试环境 win7 JQuery-3.2.1.min ...

  10. 用XHR简单封装一个axios

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...