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 from = "zsq@163.com";
private static final String fromName = "测试公司";
private static final String charSet = "utf-8";
private static final String username = "zsq@163.com";
private static final String password = "123456"; private static Map<String, String> hostMap = new HashMap<String, String>();
static {
//
hostMap.put("smtp.126", "smtp.126.com");
hostMap.put("smtp.qq", "smtp.qq.com"); //
hostMap.put("smtp.163", "smtp.163.com"); // sina
hostMap.put("smtp.sina", "smtp.sina.com.cn"); // tom
hostMap.put("smtp.tom", "smtp.tom.com"); //
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!");
} } /**
* 发送普通邮件
* @param hostIp 邮件服务器地址
* @param sendMailAddr 发送发邮箱地址
* @param sendUserName 发送方姓名
* @param username 邮箱用户名
* @param password 邮箱密码
* @param toMailAddr 收信人邮箱地址
* @param subject email主题
* @param message 发送email信息
*/
public static boolean sendCommonMail(String hostIp, String sendMailAddr, String sendUserName, String username, String password,String toMailAddr, String subject,
String message) {
HtmlEmail hemail = new HtmlEmail();
boolean flag;
try { hemail.setHostName(hostIp);
hemail.setSmtpPort(getSmtpPort(sendMailAddr));
hemail.setCharset(charSet);
hemail.addTo(toMailAddr);
hemail.setFrom(sendMailAddr, sendUserName);
hemail.setAuthentication(username, password);
hemail.setSubject(subject);
hemail.setMsg(message);
hemail.send();
flag=true;
System.out.println("email send true!"); } catch (Exception e) {
e.printStackTrace();
flag=false;
System.out.println("email send error!");
} return flag;
} 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"));
} }
注意:要想发送邮件还必须在服务器上创建一个邮件服务器和本地安装接收邮件客户端 (FoxmailSetup.exe + hMailServer.exe)!
具体的安装和配置参考: https://www.cnblogs.com/zhaosq/p/11088787.html
Java 实现 HtmlEmail 邮件发送功能的更多相关文章
- SpringBoot 2.X从0到1实现邮件发送功能
Spring中提供了JavaMailSender接口实现邮件发送功能,在SpringBoot2.X中也封装了发送邮件相关的Starter并且提供了自动化配置. 本文目录 一.添加对应的Starter二 ...
- spring-boot-route(二十二)实现邮件发送功能
在项目开发中,除了需要短信验证外,有时候为了节省 短信费也会使用邮件发送.在Spring项目中发送邮件需要封装复杂的消息体,不太方便.而在Spring Boot项目中发送邮件就太简单了,下面一起来看看 ...
- .NET开发邮件发送功能的全面教程(含邮件组件源码)
今天,给大家分享的是如何在.NET平台中开发“邮件发送”功能.在网上搜的到的各种资料一般都介绍的比较简单,那今天我想比较细的整理介绍下: 1) 邮件基础理论知识 2) ...
- 用ASP.NET Core 1.0中实现邮件发送功能-阿里云邮件推送篇
在上篇中用MailKit实现了Asp.net core 邮件发送功能,但一直未解决阿里云邮件推送问题,提交工单一开始的回复不尽如人意,比如您的网络问题,您的用户名密码不正确等,但继续沟通下阿里云客户还 ...
- redmine邮件发送功能配置详解
redmine的邮件发送功能还是很有用的.像项目有更新啦,任务分配啦,都能邮件发送的相关责任人.我自己在linux服务器上安装并启动了redmine后,邮件一直发送了不了.查了网上的资料,都是讲修改下 ...
- .NET开发邮件发送功能
.NET开发邮件发送功能 今天,给大家分享的是如何在.NET平台中开发“邮件发送”功能.在网上搜的到的各种资料一般都介绍的比较简单,那今天我想比较细的整理介绍下: 1) 邮件基础理论知 ...
- shell邮件发送功能实现
本文中以163邮箱为例,测试shell邮件发送功能.常见的工具有:mailx.sendmail.mutt等. 1.设置邮件客户端 (1)启用pop3.smtp服务,以支持第三方客户端支持 (2)设置授 ...
- Spring进阶—如何用Java代码实现邮件发送(一)
相关文章: <Spring进阶—如何用Java代码实现邮件发送(二)> 在一些项目里面如进销存系统,对一些库存不足发出预警提示消息,招聘网站注册用户验证email地址等都需要用到邮件发送技 ...
- System.Net邮件发送功能踩过的坑
System.Net邮件发送功能踩过的坑 目录 System.Net邮件发送功能踩过的坑 1.EazyEmail邮件发送类库 2.邮件发送授权码与邮件密码 3.通过邮件密码来发送邮件 4.Wiresh ...
随机推荐
- BITCTF-MISC
MISC 以此笔记来记录本菜鸡做misc的历程 签到85 首先看题 提示base85 打开kali,使用python的base64库来解码(内有base85解码) (其实只要输python3即可 我还 ...
- mysql数据库多表查询where与内连接inner join的区别
按理说where是对前面的笛卡尔积进行过滤,工作量大增,inner join则不会.但我实际测试了一下,两种查询耗时基本相等,甚至where还快一些,多次测试后基本如此. 如下图: where: in ...
- Oracle - SPM固定执行计划(二)
一.前言 前面文章(https://www.cnblogs.com/ddzj01/p/11365541.html)给大家介绍了当一条sql有多个执行计划时,如何通过spm去绑定其中一条执行计划.本文将 ...
- javaWeb核心技术第十篇之Filter
Web中有三大组件(需要配置web.xml) servlet:服务器端的小程序. Filter(过滤器):运行在服务器,对请求的资源进行过滤,对响应进行包装. 经典案例: 自动登录,网站全局编码,非法 ...
- Vue.js+vue-element搭建属于自己的后台管理模板:更深入了解Vue.js(三)
前言 上一章我们介绍了关于Vue实例中一些基本用法,但是组件.自定义指令.Render函数这些放到了本章来介绍,原因是它们要比前面讲的要难一些,组件是Vue.js最核心的功能,学习使用组件也是必不可少 ...
- layui省市区三级联动城市选择
基于layui框架制作精美的省市区下拉框三级联动菜单选择, 支持三级联动城市选择,点击提交获取选中值代码. 示例图如下: 资源链接: https://pan.baidu.com/s/1s6l8iDBE ...
- Python 读取照片的信息:拍摄时间、拍摄设备、经纬度等,以及根据经纬度通过百度地图API获取位置
通过第三方库exifread读取照片信息.exifread官网:https://pypi.org/project/ExifRead/ 一.安装exifreadpip install exifread ...
- 20个常用的JavaScript字符串方法
摘要: 玩转JS字符串. 原文:JS 前20个常用字符串方法及使用方式 译者:前端小智 Fundebug经授权转载,版权归原作者所有. 本文主要介绍一些最常用的JS字符串函数. 1. charAt(x ...
- sqlserver刷新视图
sqlserver 用于刷新当前数据库所有视图的存储过程 create procedure dbo.proc_refreshview as begin ) declare cur_view curso ...
- 实战项目-用例评审-问题总结-Dotest-董浩
实战项目-用例评审-问题总结 内部班项目用例评审,总结的问题:供大家参考!提升用例最好的方式,可以互相执行下(评审),就会明白自己的差距或者需要避免的点在哪里.(前提是会) 1)覆盖率 原型中提到的一 ...