2019独角兽企业重金招聘Python工程师标准>>>

发邮件

package org.jeecgframework.core.util;import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;import org.apache.commons.mail.HtmlEmail;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;import freemarker.template.Configuration;
import freemarker.template.Template;
/*** * **/
public class SendMailUtil
{//private static final String smtphost = "192.168.1.70";private static final String from = "zhangdh@163.com";private static final String fromName = "测试公司";private static final String charSet = "utf-8";private static final String username = "zhangdh@163.com";private static final String password = "123456";private static Map<String, String> hostMap = new HashMap<String, String>();static {// 126hostMap.put("smtp.126", "smtp.126.com");// qqhostMap.put("smtp.qq", "smtp.qq.com");// 163hostMap.put("smtp.163", "smtp.163.com");// sinahostMap.put("smtp.sina", "smtp.sina.com.cn");// tomhostMap.put("smtp.tom", "smtp.tom.com");// 263hostMap.put("smtp.263", "smtp.263.net");// yahoohostMap.put("smtp.yahoo", "smtp.mail.yahoo.com");// hotmailhostMap.put("smtp.hotmail", "smtp.live.com");// gmailhostMap.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");// 模板内容转换为stringString htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);org.jeecgframework.core.util.LogUtil.info(htmlText);hemail.setMsg(htmlText);hemail.send();org.jeecgframework.core.util.LogUtil.info("email send true!");} catch (Exception e) {e.printStackTrace();org.jeecgframework.core.util.LogUtil.info("email send error!");}}/*** 发送普通邮件* @param toMailAddr 收信人地址* @param subject email主题* @param message 发送email信息  */public static void sendCommonMail(String toMailAddr, String subject, String message) {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);hemail.setMsg(message);hemail.send();org.jeecgframework.core.util.LogUtil.info("email send true!");} catch (Exception e) {e.printStackTrace();org.jeecgframework.core.util.LogUtil.info("email send error!");}}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");// 模板内容转换为stringhtmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);org.jeecgframework.core.util.LogUtil.info(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("\\", "/");org.jeecgframework.core.util.LogUtil.info(path);return path;}private static String getFileName(String path) {path = path.replace("\\", "/");org.jeecgframework.core.util.LogUtil.info(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);}org.jeecgframework.core.util.LogUtil.info("realPath----->"+realPath);return realPath;}
//  private static File getFile(String path){
//      File file = SendMail.class.getClassLoader().getResource("mailtemplate/test.ftl").getFile();
//      return file;
//  }
//  public static void main(String[] args){
//    HtmlEmail hemail = new HtmlEmail();
//      try {
//        hemail.setHostName("smtp.exmail.qq.com");
//        hemail.setCharset("utf-8");
//        hemail.addTo("fly.1206@qq.com");
//        hemail.setFrom("zhoujunfeng@et-bank.com", "周俊峰");
//        hemail.setAuthentication("zhoujunfeng@et-bank.com", "31415926@aa");
//        hemail.setSubject("sendemail test!");
//        hemail.setMsg("<a href=\"http://www.google.cn\">谷歌</a><br/>");
//        hemail.send();
//        org.jeecgframework.core.util.LogUtil.info("email send true!");
//      } catch (Exception e) {
//        e.printStackTrace();
//        org.jeecgframework.core.util.LogUtil.info("email send error!");
//      }Map<String, Object> map = new HashMap<String, Object>();map.put("subject", "测试标题");map.put("content", "测试 内容");String templatePath = "mailtemplate/test.ftl";sendFtlMail("test@et-bank.com", "sendemail test!",templatePath, map);//    org.jeecgframework.core.util.LogUtil.info(getFileName("mailtemplate/test.ftl"));}}

转载于:https://my.oschina.net/budaoniu/blog/605592

java重复造轮子系列篇------发送邮件sendEmail相关推荐

  1. java重复造轮子系列篇-----时间date

    2019独角兽企业重金招聘Python工程师标准>>> 时间操作工具类 package org.jeecgframework.core.util;import java.beans. ...

  2. 重复造轮子系列——基于FastReport设计打印模板实现桌面端WPF套打和商超POS高度自适应小票打印...

    重复造轮子系列--基于FastReport设计打印模板实现桌面端WPF套打和商超POS高度自适应小票打印 一.引言 桌面端系统经常需要对接各种硬件设备,比如扫描器.读卡器.打印机等. 这里介绍下桌面端 ...

  3. 还在重复造轮子?Java开发人员必知必会的20种常用类库和API

    介绍 一个有经验的Java开发人员特征之一就是善于使用已有的轮子来造车.<Effective Java>的作者Joshua Bloch曾经说过:"建议使用现有的API来开发,而不 ...

  4. 不是“重复”造轮子,百度飞桨框架2.0如何俘获人心

    2016 年,百度 PaddlePaddle 打响了国产深度学习框架开源的第一枪. 2019 年 4 月,在 Wave Summit 深度学习开发者峰会上,首次发布了PaddlePaddle 的中文名 ...

  5. Spring Boot并不重复“造轮子”

    2.1 Spring Boot简介 Spring Boot是由Pivotal团队提供的基于Spring的全新框架,其设计目的是简化Spring应用的搭建和开发过程.该框架遵循"约定大于配置& ...

  6. 51年被发现9次,陶哲轩证明的公式成了重复造轮子?事情并没有这么简单

    晓查 栗子 发自 凹非寺  量子位 报道 | 公众号 QbitAI 在科学探索的过程中,"重复造轮子"从来就不新鲜. 最知名如牛顿和莱布尼茨,各自独立发明了微积分:而计算机领域,也 ...

  7. 程序员到底要不要重复造轮子?

    分享一波:程序员赚外快-必看的巅峰干货 关于这个话题,现在这里阐述立场:就公司工作而言,不建议重复造轮子.就个人技术而言,强烈建议造轮子! 程序员圈子里流行这么一句话:"不要重复造轮子&qu ...

  8. json转string工具_不要再重复造轮子了,这款开源工具类库贼好使!

    Hutool是一个小而全的Java工具类库,它帮助我们简化每一行代码,避免重复造轮子.如果你有需要用到某些工具类的时候,不妨在Hutool里面找找.本文总结了平时常用的16个工具类,希望对大家有所帮助 ...

  9. 到底是否应该重复造轮子

    引言 之所以谈起这个话题,是因为和新公司同事的一次交流.他是LZ当时二面的面试官(以下简称CZ),看过LZ的github,因此知道LZ正在尝试写一个redis的Java客户端.在交流的过程中,CZ给L ...

最新文章

  1. error LNK2019: 无法解析的外部符号,该符号在函数 _main 中被引用的解决方法
  2. 阿里三面被挂,幸获内推,历经5轮终于拿到口碑offer
  3. 史上最详细的RocketMq 下单支付案例 分享
  4. 石川es6课程---5、函数-参数
  5. 通向高可扩展性之路(谷歌篇)
  6. android html audio,html5 用audio的playbackRate属性控制播放速度在安卓手机不起作用?...
  7. ASP.Net服务性能优化原则
  8. 宿迁学计算机的学校,宿迁计算机学校
  9. 计算机毕设-文献摘要,毕设摘要翻译,要人工翻译,不要电脑网站翻译的。
  10. es6 Proxy 简介
  11. Java学习笔记2.3.4 运算符与表达式 - 逻辑运算符
  12. HDU 1026 广度优先搜索,BFS+路径的记录
  13. php人才招聘cms,骑士cms-php+mysql高效人才招聘系统
  14. 【外贸建站规则】外贸网站建站流程有哪些?需要注意什么? (上)
  15. 【opencv】动态背景下运动目标检测 SURF配准差分
  16. java里获取当前月份_Java如何获取当前月份的名称?
  17. 使用百度云加速服务进行配置网站https证书(例如:阿里云免费SSL证书)
  18. jackson学习之五:JsonInclude注解,颠覆认知
  19. Spring Gateway路由网关
  20. 教育子女正确方式(楼天成父母教育孩子)

热门文章

  1. CentOs 设置静态IP 方法[测试没问题]
  2. Linux之find常用命令汇总
  3. linux之登录式shell和非登录式shell
  4. Java线程池ExecutorService中重要的方法
  5. Linux学习笔记十七——Linux系统启动流程
  6. Matlab中数组下标是logical,如何处理?
  7. poj1068Parencodings
  8. Chrome中使用showModalDialog无法接收返回值,解决方案
  9. 842. 将数组拆分成斐波那契序列
  10. 02-05 从c到c++