目前springboot 使用的非常广泛,所以这段时间构建的服务都是基于springboot的,这次邮件组件也是使用的spring-boot-starter-mail。
邮件发送一般使用的也是别人的代理服务,我们使用的也是这些服务的代理,比如代发QQ邮件,163邮件,腾讯企业邮,这三个邮件服务有些细小区别,文章尾部会说明。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
几个关键的maven依赖和配置文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--有可能会报ognl缺失 处理模板文件必备-->
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.0.8</version>
</dependency>
springboot的properties文件
<!--springboot的properties文件-->
# //邮箱服务器地址
spring.mail.default-encoding=UTF-8
#//以谁来发送邮件
mail.fromMail.addr=626158413@qq.com
######qq邮箱########
spring.mail.host=smtp.qq.com
spring.mail.username=626158413@qq.com
#QQ邮箱授权码
spring.mail.password=wdcnoppnituvbdjf
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
#QQ邮箱和163邮箱的区别是,qq需要设置授权码而不是密码
#####163邮箱########
#spring.mail.host=smtp.163.com
#spring.mail.username=*****@163.com
##163邮箱密码
#spring.mail.password=!@#$%^&*
#spring.mail.properties.mail.smtp.auth=true
#spring.mail.properties.mail.smtp.starttls.enable=true
#spring.mail.properties.mail.smtp.starttls.required=true
#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
#thymeleaf end
测试类的代码:
package com.example.demo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailtestApplicationTests {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private JavaMailSender mailSender;
@Qualifier("templateEngine")
@Autowired
private TemplateEngine templateEngine;
@Value("${mail.fromMail.addr}")
private String from;
@Test
public void contextLoads() {
// 发送普通html
// String content="<html>\n" +
// "<body>\n" +
// " <h3>hello world ! 这是一封Html邮件!</h3>\n" +
// "</body>\n" +
// "</html>";
//
// this.sendSimpleMailWithHtml("626158413@qq.com","test simple mail",content);
// 发送模板
// Context context = new Context();
// context.setVariable("id", "66666666666666666666");
// context.setVariable("param1", "我是param1");
// context.setVariable("param2", "我是param2");
//
// String emailContent = templateEngine.process("emailPage", context);
// System.out.println(emailContent);
// this.sendSimpleMailWithHtml("626158413@qq.com","测试模板",emailContent);
}
private void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
try {
mailSender.send(message);
logger.info("简单邮件已经发送。");
} catch (Exception e) {
logger.error("发送简单邮件时发生异常!", e);
}
}
/**
* 发送简单文本邮件
* @param to 发送给谁 邮件地址 XX@ss.com
* @param subject 标题
* @param content 主题内容
*/
private void sendSimpleMailWithHtml(String to, String subject, String content) {
MimeMessage message = mailSender.createMimeMessage();
try {
//true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(message);
logger.info("html邮件发送成功");
} catch (MessagingException e) {
logger.error("发送html邮件时发生异常!", e);
}
}
/**
* 发送html内容的邮件
* @param to 发送给谁 邮件地址 XX@ss.com
* @param subject 标题
* @param content 主题内容
*/
private void sendSimpleMailWithThymeleafHtml(String to, String subject, String content) {
MimeMessage message = mailSender.createMimeMessage();
TemplateEngine templateEngine = new TemplateEngine();
//创建邮件正文
Context context = new Context();
context.setVariable("id", "006");
String emailContent = templateEngine.process("emailTemplate", context);
logger.info("html邮件发送成功");
}
}
模板文件
在resorces/templates下创建emailTemplate.html (可自定义样式)
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
<h3 style="color: red">hahahahahahahahha</h3>
<h4 th:text="${param1}" style="color: blue">hahahahahahahahha</h4>
<h4 th:text="${param2}" style="color: blue">hahahahahahahahha</h4>
您好,这是验证邮件,请点击下面的链接完成验证,<br/>
<a href="#" th:href="@{ http://www.ityouknow.com/neo/{id}(id=${id}) }">激活账号</a>
</body>
</html>
关于三种邮件服务使用时:
如果是代理发送腾讯企业邮箱,需要注意
服务地址改为smtp.exmail.qq.com
端口不是官方文档说的465而是25 (参考foxmail的默认配置等)
密码是授权码
要使用加密协议
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true