java HtmlEmail发送邮件工具类
- package com.sh.xrsite.common.utils;
- 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 = "test@163.com";
- private static final String fromName = "测试公司";
- private static final String charSet = "utf-8";
- private static final String username = "home@163.com";
- private static final String password = "123456";
- private static Map<String, String> hostMap = new HashMap<String, String>();
- static {
- // 126
- hostMap.put("smtp.126", "smtp.126.com");
- hostMap.put("smtp.qq", "smtp.qq.com");
- // 163
- hostMap.put("smtp.163", "smtp.163.com");
- // sina
- hostMap.put("smtp.sina", "smtp.sina.com.cn");
- // tom
- hostMap.put("smtp.tom", "smtp.tom.com");
- // 263
- hostMap.put("smtp.263", "smtp.263.net");
- // yahoo
- hostMap.put("smtp.yahoo", "smtp.mail.yahoo.com");
- // hotmail
- hostMap.put("smtp.hotmail", "smtp.live.com");
- // gmail
- hostMap.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");
- // 模板内容转换为string
- String htmlText = FreeMarkerTemplateUtils
- .processTemplateIntoString(template, map);
- System.out.println(htmlText);
- hemail.setMsg(htmlText);
- hemail.send();
- System.out.println("email send true!");
- } catch (Exception e) {
- e.printStackTrace();
- System.out.println("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();
- System.out.println("email send true!");
- } catch (Exception e) {
- e.printStackTrace();
- System.out.println("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");
- // 模板内容转换为string
- htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(
- template, map);
- System.out.println(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("\\", "/");
- System.out.println(path);
- return path;
- }
- private static String getFileName(String path) {
- path = path.replace("\\", "/");
- System.out.println(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);
- }
- System.out.println("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.163.com");
- hemail.setCharset("utf-8");
- hemail.addTo("收件邮箱地址");
- hemail.setFrom("发件邮箱地铁", "网易");
- hemail.setAuthentication("wang_yi@163.com", "发件邮箱密码");
- hemail.setSubject("sendemail test!");
- hemail.setMsg("<a href=\"http://www.google.cn\">谷歌</a><br/>");
- hemail.send();
- System.out.println("email send true!");
- } catch (Exception e) {
- e.printStackTrace();
- System.out.println("email send error!");
- }
- // Map<String, Object> map = new HashMap<String, Object>();
- // map.put("subject", "测试标题");
- // map.put("content", "测试 内容");
- // String templatePath = "mailtemplate/test.ftl";
- // sendFtlMail("test@163.com", "sendemail test!", templatePath, map);
- // System.out.println(getFileName("mailtemplate/test.ftl"));
- }
- }
java HtmlEmail发送邮件工具类的更多相关文章
- JAVA发送邮件工具类
import java.util.Date;import java.util.Properties; import javax.mail.BodyPart;import javax.mail.Mess ...
- Jmail发送邮件工具类
好久没更新博客了,实在是拖延症严重啊,好可怕,先更新个工具类吧,之前写的发送邮件的小工具,话不多说上代码 import lombok.extern.slf4j.Slf4j; import java.u ...
- HttpTool.java(在java tool util工具类中已存在) 暂保留
HttpTool.java 该类为java源生态的http 请求工具,不依赖第三方jar包 ,即插即用. package kingtool; import java.io.BufferedReader ...
- java文件处理工具类
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedRead ...
- java格式处理工具类
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOExceptio ...
- Java 敏感词过滤,Java 敏感词替换,Java 敏感词工具类
Java 敏感词过滤,Java 敏感词替换,Java 敏感词工具类 =========================== ©Copyright 蕃薯耀 2017年9月25日 http://www ...
- Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类
Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...
- 使用java的Calendar工具类获取到本月的第一天起始时间和最后一天结束时间。
1.使用java的Calendar工具类获取到本月的第一天起始时间和最后一天结束时间. package com.fline.aic.utils; import java.text.DateFormat ...
- JAVA 8 日期工具类
JAVA 8 日期工具类 主题描述 JAVA中日期时间的历史 代码成果 主题描述 JAVA的日期时间一直比较混乱,本来以为joda会是巅峰,但是JAVA 8改变了我的思想.但是即便在JAVA 8面前, ...
随机推荐
- 06.do-while循环的练习
练习1: namespace _09.do_while循环练习01 { class Program { static void Main(string[] args) { //计算1到100之间的整数 ...
- openLayers3 中实现多个Overlay
此篇的目的是为了记录下用Overlay的一些操作. 其实实现多个就是创建多个div,然后给每个div绑定Overlay. //页面加载完函数 --显示个关键点的名称 window.onload = f ...
- redux基本使用
redux数据流向 基本使用
- Celery-------项目目录
在实际应用中Celery的目录是有规则的 要满足这样的条件才可以 目录Celery_task这个名字可以随意,但是这个目录下一定要有一个celery.py这个文件 from celery import ...
- 利用函数回调获取setInterval中返回的值
我们都知道,定时器里面想返回值如果你用return根本没作用,那么怎么拿到定时器所返回的值呢, 现在只需要利用回调函数,给主函数传一个函数类型的参数callback,然后把想要返回的num再传给cal ...
- PLC-Heart
- Android 环信(Android)设置头像和昵称的方法
最近,经常有朋友问到,如何集成环信头像,怎么才能快速显示头像,因时间紧急,很多朋友都没有时间慢慢的研究代码,这里大家稍微花10分钟看一下文章,看完后再花5分钟改一下代码,即可达到你们所要的效果. 当然 ...
- 织梦CMS调用文章列表时,怎么显示短时间格式
问题描述:织梦在上传文章的时候,默认的上传文章的时间格式都是年.月.日.小时.分钟.秒的格式,怎么才能实现仅显示年.月.日的格式呢? 解决方法: [field:pubdate function=&qu ...
- ubuntu安装google test
google test 简称gtest,是一个C/C++的单元测试框架,它的代码在github仓库,使用起来还是挺方便的. 安装 先确保PC上有安装cmake: sudo cmake --versio ...
- C语言 条件编译(if )
#include <stdio.h> #define NUM -1 int main(int argc, const char * argv[]) { #if NUM > 0 pri ...