1.依赖

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.5.RELEASE</version>
</dependency>
<!--JavaMail-->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency> <!--基于Freemarker的邮件模板 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>

2.配置

#启用邮件通知
mail.enabled=true
#服务器主机名
mail.smtp.host=mail.163.com
#邮件服务端口(不填就是用默认端口),smtp默认端口为25
mail.smtp.port=587
#邮箱地址
mail.smtp.username=xxxx
#你的授权码,有些邮箱服务器使用密码就可以了
mail.smtp.password=xxxxx
#编码格式
mail.smtp.defaultEncoding=UTF-8
#是否进行用户名密码校验
mail.smtp.auth=true
#发送邮件日志级别
mail.smtp.debug=true

3.参数封装类



import java.util.List;
import java.util.Properties; /**
* 发送邮件参数
* @author Created by niugang on 2019/10/15/9:54
*/
public class MailSendParameters {
/**
* 接收者
*/
private List<String> receivers;
/**
* 会议主题
*/
private String subject; /**
* 会议描述
*/
private String description; /**
* 会议时间
*/
private String time; /**
* 会议地点
*/
private String address; /**
* 发送者姓名
*/
private String senderName; public List<String> getReceivers() {
return receivers;
} public void setReceivers(List<String> receivers) {
this.receivers = receivers;
} public String getSubject() {
return subject;
} public void setSubject(String subject) {
this.subject = subject;
} public String getDescription() {
return description;
} public void setDescription(String description) {
this.description = description;
} public String getTime() {
return time;
} public void setTime(String time) {
this.time = time;
} public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} public String getSenderName() {
return senderName;
} public void setSenderName(String senderName) {
this.senderName = senderName;
} }

4.核心发送工具类

/**
* @author Created by niugang on 2019/10/14/16:54
*/ public class MailSendUtil { private static final Logger logger = LoggerFactory.getLogger(MailSendUtil.class); private static final String BOOLEAN_REGEX = "^false$|^true$"; private static final String MAIL_CONF_PATH = "/home/xdja/conf/meeting/mail.properties"; private static final Pattern PATTERN = Pattern.compile(BOOLEAN_REGEX); private static Properties mailProperties; /**
* 判断邮件功能是否开启,默认邮件功能为关闭的
* true 开启
* false 关闭
*
* @return boolean
*/
public static boolean isMailEnabled() {
readPropertiesFile();
String mailEnabled = mailProperties.getProperty("mail.enabled");
if (StringUtils.isNotBlank(mailEnabled)) {
String mailEnabledLowerCase = mailEnabled.toLowerCase();
Matcher matcher = PATTERN.matcher(mailEnabledLowerCase);
if (!matcher.matches()) {
throw new IllegalArgumentException("mail.enabled parameter format error,parameter true or false, case ignored");
}
boolean aBoolean = Boolean.parseBoolean(mailEnabled);
if (!aBoolean) {
logger.info("mail.enabled is false ,no need to send email");
}
return aBoolean;
}
return false;
} /**
* 读取配置文件
*/
private static void readPropertiesFile() {
try {
mailProperties = readProperties();
} catch (FileNotFoundException e) {
logger.error("Properties file not found");
}
if (mailProperties == null) {
throw new NullPointerException("Properties file must not be null");
} } /**
* 发送邮件
*/
public static void sendMail(final MailSendParameters mailSendParameters) {
if (mailProperties == null) {
readPropertiesFile();
}
List<String> receivers = mailSendParameters.getReceivers();
if (receivers.isEmpty()) {
throw new NullPointerException("Mail receiver must not be null");
}
if (mailSendParameters.getSubject() == null) {
throw new NullPointerException("Mail subject must not be null");
} try {
String[] receiversArray = mailSendParameters.getReceivers().toArray(new String[0]);
JavaMailSender javaMailSender = getJavaMailSender(mailProperties);
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
//发送者 必须和配置的 mail.smtp.username 一样
mimeMessageHelper.setFrom(mailProperties.getProperty("mail.smtp.username"));
//接收者
mimeMessageHelper.setTo(receiversArray);
//邮件主题
mimeMessageHelper.setSubject(mailSendParameters.getSubject());
//邮件内容
mimeMessageHelper.setText(getText(mailSendParameters), true); javaMailSender.send(mimeMessage);
logger.info("Meeting [mail] send success...");
} catch (Exception e) {
logger.info("Meeting [mail] send failed...",e);
} } /**
* 创建发送对象
*
* @return JavaMailSender
*/
private static JavaMailSender getJavaMailSender(Properties paramProp) {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost(paramProp.getProperty("mail.smtp.host"));
javaMailSender.setUsername(paramProp.getProperty("mail.smtp.username"));
javaMailSender.setPassword(paramProp.getProperty("mail.smtp.password"));
String portStr = paramProp.getProperty("mail.smtp.port");
if (StringUtils.isNotBlank(portStr)) {
javaMailSender.setPort(Integer.parseInt(portStr));
}
String defaultEncoding = paramProp.getProperty("mail.smtp.defaultEncoding");
if (StringUtils.isNotBlank(defaultEncoding)) {
javaMailSender.setDefaultEncoding(defaultEncoding);
}
String auth = paramProp.getProperty("mail.smtp.auth");
String debug = paramProp.getProperty("mail.smtp.debug");
Properties properties = new Properties();
properties.setProperty("mail.smtp.auth", StringUtils.isNotBlank(auth) ? auth : "true");
properties.setProperty("mail.debug", StringUtils.isNotBlank(debug) ? debug : "true");
javaMailSender.setJavaMailProperties(properties);
return javaMailSender;
} /**
* 读取freemarker模板的方法
*/
private static String getText(MailSendParameters mailSendParameters) {
String txt = "";
try {
//freemarker包
Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
//设置模板加载文件夹
configuration.setDirectoryForTemplateLoading(new File(ResourceUtils.getURL("classpath:").getPath() + "template"));
Template template = configuration.getTemplate("mail.ftl"); // 通过map传递动态数据
Map<String, Object> map = new HashMap<>();
map.put("subject", mailSendParameters.getSubject());
map.put("time", mailSendParameters.getTime());
map.put("address", mailSendParameters.getAddress());
map.put("sponsor", mailSendParameters.getSenderName());
map.put("description", mailSendParameters.getDescription());
// 解析模板文件
txt = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
} catch (Exception e) {
logger.error("Create send [mail] template exception:{}", e);
throw new ServiceException("Create send [mail] template exception");
} return txt;
} /**
* 读取发送邮件配置,实时读取,为了修改配置不重启服务<br/>
*
* 或者使用WatchService 启动线程对文件状态进行监控<br/>
* <a href="https://blog.csdn.net/niugang0920/article/details/102594552">
* https://blog.csdn.net/niugang0920/article/details/102594552</a>
*
* @return Properties
* @throws FileNotFoundException FileNotFoundException
*/
private static Properties readProperties() throws FileNotFoundException {
Properties properties = new Properties();
File file = new File(MAIL_CONF_PATH);
if (!file.exists()) {
logger.error(MAIL_CONF_PATH + "is not exist");
throw new FileNotFoundException(MAIL_CONF_PATH + "is not exist");
}
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
properties.load(fileInputStream);
} catch (IOException e) {
logger.error("Read [mail] properties failed:{}", e);
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
logger.error("Close FileInputStream failed:{}", e);
}
}
return properties;
} }

5.发送模板

在src/resources下新建template文件夹

添加mail.ftl模板

<table width="700" border="1" cellspacing="0" cellpadding="0">
<tr>
<td style="text-align: center">
会议主题:
</td>
<td style="font-weight: bold;text-align: center">
${subject!""}
</td>
</tr>
<tr>
<td style="text-align: center" width="100">
会议时间:
</td>
<td style="font-weight: bold;text-align: center">
${time!""}
</td>
</tr>
<tr>
<td style="text-align: center">
会议地点:
</td>
<td style="font-weight: bold;text-align: center">
${address!""}
</td>
</tr> <tr>
<td style="text-align: center">
会议主持人/组织者:
</td>
<td style="text-align: center">
${sponsor!""}
</td>
</tr> <tr>
<td style="text-align: center">
会议描述:
</td>
<td style="text-align: center">
${description!""}
</td>
</tr> <tr>
<td style="text-align: center">
与会人员:
</td>
<td style="text-align: center">
如收件人
</td>
</tr> </table>

6.调用测试

在controller中进行调用测试,以下为调试代码

  MailSendParameters mailSendParameters = new MailSendParameters();
mailSendParameters.setAddress("4号会议室");
mailSendParameters.setDescription("学习经验分享");
mailSendParameters.setSubject("分布式微服务技术分享交流会");
mailSendParameters.setReceivers(new ArrayList<String>() {
{ ////收件人邮箱
add("xxxxxxx");
} }
);
mailSendParameters.setSenderName("张三");
mailSendParameters.setTime("2019年10月15日星期二 19:00-20:00");
if(MailSendUtil.isMailEnabled()){
MailSendUtil.sendMail(mailSendParameters);
}

7.效果

微信公众号

基于Spring封装的Javamail实现邮件发送的更多相关文章

  1. Spring MVC+javamail实现邮件发送

    Spring MVC+javamail实现邮件发送 开启邮箱的POP3/SMTP服务(这里以QQ邮箱举例) 设置 --> 账户 -- > 开启POP3/STMP服务,然后得到一个授权码. ...

  2. Springboot+Javamail实现邮件发送

    Springboot+Javamail实现邮件发送 使用的是spring-context-support-5.2.6.RELEASE.jar里的javamail javamail 官方文档:javam ...

  3. 基于javaMail的邮件发送--excel作为附件

    基于JavaMail的Java邮件发送 Author xiuhong.chen@hand-china.com Desc 简单邮件发送 Date 2017/12/8 项目中需要根据物料资质的状况实时给用 ...

  4. Java 基于javaMail的邮件发送(支持附件)

    基于JavaMail的Java邮件发送Author xiuhong.chen@hand-china.com Desc 简单邮件发送 Date 2017/12/8 项目中需要根据物料资质的状况实时给用户 ...

  5. Java 基于JavaMail的邮件发送

    http://blog.csdn.net/xietansheng/article/details/51673073 http://blog.csdn.net/xietansheng/article/d ...

  6. Springboot使用javaMail进行邮件发送

    导入相关依赖 <!--邮件发送--> <dependency> <groupId>javax.mail</groupId> <artifactId ...

  7. 使用 spring封装的javamail linux服务器发送邮件失败解决

    原文参考:https://blog.csdn.net/a540891049/article/details/79385471 由于某些平台的linxu服务器为了安全起见 屏蔽了发送邮件的常用端口 25 ...

  8. 使用Javamail实现邮件发送功能

    目录 相关的包 编写工具类 环境说明 @(使用Javamail实现邮件发送功能) 相关的包 activation.jar javax.mail.jar mail包建议使用高版本写的包,否则可能会发空白 ...

  9. Java系列--第八篇 基于Maven的SSME之定时邮件发送

    关于ssme这个我的小示例项目,想做到麻雀虽小,五脏俱全,看到很多一些web都有定时发送邮件的功能,想我ssme也加入一下这种功能,经查询相关文档,发现spring本身自带了一个调度器quartz,下 ...

随机推荐

  1. U盘还原系统

    相信现在不少的人已经开始使用U盘作为启动盘来安装系统,说起来这可比用光盘装系统可是方便多了.毕竟U盘可以随身携带,至于光盘嘛,就不多说了.       可是还有许多人对U盘安装系统还是有些陌生的感觉. ...

  2. linux包之nmap之ncat命令

    [root@ka1che225 ~]# which nc/usr/bin/nc[root@ka1che225 ~]# which ncat/usr/bin/ncat[root@ka1che225 ~] ...

  3. ip2long之后有什么好处?

    ip2long需要bigint来存储,而且在32位和64位系统中存储方式还有区别: 而保存成字符串,只需要char20即可. 那么,ip2long好处在哪? 做投票项目的时候,将ip地址处理后用int ...

  4. 【原生JS】评论编辑器 文本操作

    效果图: HTML: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> ...

  5. 2019-3-8-win10-uwp-渲染原理-DirectComposition-渲染

    title author date CreateTime categories win10 uwp 渲染原理 DirectComposition 渲染 lindexi 2019-03-08 09:18 ...

  6. Nutch2.3 编译

    $ antBuildfile: build.xmlTrying to override old definition of task javac ivy-probe-antlib: ivy-downl ...

  7. java throw

    自行抛出一个异常对象,抛出异常类的对象: 若throw抛出的是Runtime异常: 程序可以显示使用try...catch来捕获并处理,也可以不管,直接交给方法调用者处理: 若throw抛出Check ...

  8. linux tasklet工作队列

    工作队列是, 表面上看, 类似于 taskets; 它们允许内核代码来请求在将来某个时间调用 一个函数. 但是, 有几个显著的不同在这 2 个之间, 包括: tasklet 在软件中断上下文中运行的结 ...

  9. 牛客多校第四场sequence C (线段树+单调栈)

    牛客多校第四场sequence C (线段树+单调栈) 传送门:https://ac.nowcoder.com/acm/contest/884/C 题意: 求一个$\max {1 \leq l \le ...

  10. Windows Server Core Remote Manage Hyper-V

    原帖:https://serverfault.com/questions/852144/how-do-i-remotely-manage-hyper-v-2016-standalone-via-win ...