PageRenderTime 62ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/thinkgem/jeesite/common/utils/SendMailUtil.java

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