SpringBoot如何实现邮件发送呢?
下文笔者讲述使用SpringBoot发送(简单邮件、带附件邮件、带图片资源的邮件、使用邮件模板)的方法及示例分享,如下所示
创建mailtemplate.ft1作为邮件模板:
SpringBoot发送邮件的实现思路
1.邮箱账户上设置 POP3/SMTP设置 2.引入相应的jar包 3.将邮件服务器的信息设置到 application.properties文件中 4.直接调用mailService发送邮件例:
发送邮件基本配置
创建项目 添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> 在application.properties中进行配置 #邮件服务器 spring.mail.host=smtp.qq.com #端口(465或587) spring.mail.port=465 # 邮箱 spring.mail.username=xxxx@qq.com # 授权码 spring.mail.password=232324213114 spring.mail.default-encoding=UTF-8 spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory spring.mail.properties..mail.debug=true
发送简单邮件
创建一个MailService用来封装邮件的发送:
@Component
public class MailService {
@Autowired
JavaMailSender javaMailSender;
public void sendSimpleMail(String from, String to, String cc, String subject, String content){
SimpleMailMessage simpMsg = new SimpleMailMessage();
simpMsg.setFrom(from);//发送者
simpMsg.setTo(to);//收件人
simpMsg.setCc(cc);//抄送人
simpMsg.setSubject(subject);//邮件主题
simpMsg.setText(content);//邮件内容
javaMailSender.send(simpMsg);
}
}
JavaMeailSender
是SpringBoot
在MailSenderPropertiesConfiguration类中配置好
该类在mail自动配置类MailSenderAutoConfiguration中导入
所以直接注入JavaMailSender就可以使用了。
简单邮件可以直接构建一个SimpleMailMessage对象进行配置
配置完成后
通过JavaMailSender将邮件发送出去。
@RunWith(SpringRunner.class)
@SpringBootTest
class DemoApplicationTests {
@Autowired
MailService mailService;
@Test
void sendSimpleMail() {
mailService.sendSimpleMail("1xx@qq.com",
"xxxx@163.com",
"xxxxx313@qq.com",
"邮件测试主题",
"邮件测试内容");
}
}
发送带附件的邮件
发送带附件的邮件
我们只需使用attachment方法添加附件
例
public void sendAttachFileMail(String from, String to, String subject, String content, File file){
try {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content);
helper.addAttachment(file.getName(), file);
javaMailSender.send(message);
}catch (MessagingException e){
e.printStackTrace();
}
}
@Test
public void sendAttachFileMail(){
String path = this.getClass().getClassLoader().getResource("application.properties").getPath();
mailService.sendAttachFileMail("xx@qq.com",
"xxx@163.com",
"测试邮件主题",
"测试邮件内容",
new File(path));
}
发送带图片资源的邮件
邮件正文中要插入图片 需使用FileSystemResource
public void sendMailWithImg(String from, String to, String subject, String content, String[] srcPath, String[] resIds){
if(srcPath.length != resIds.length){
System.out.println("发送失败!");
return;
}
try{
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
for(int i = 0; i < srcPath.length; i++){
FileSystemResource res = new FileSystemResource(new File(srcPath[i]));
helper.addInline(resIds[i], res);
}
javaMailSender.send(message);
}catch (MessagingException e){
System.out.println("发送失败!");
}
}
//在调用MimeMessageHelper中的setText方法时
//第二个参数为true表示邮件正文是HTML格式
//该参数不传默认为false。
@Test
public void sendMailWithImg(){
String imgPaht1 = this.getClass().getClassLoader().getResource("img/2.jpg").getPath();
String imgPaht2 = this.getClass().getClassLoader().getResource("img/3.jpg").getPath();
mailService.sendMailWithImg("xxxx@qq.com",
"xxxx@163.com",
"测试邮件主题(图片)",
"<div>hello,这是一封带图片资源的邮件:" +
"这是图片1:<div><img src='cid:p01'/></div>" +
"这是图片2:<div><img src='cid:p02'/></div>" +
"</div>",
new String[]{imgPaht1, imgPaht2},
new String[]{"p01", "p02"});
}
使用FreeMarker构建邮件模板
对于格式复杂的邮件 采用字符串进行拼接 不但容易出错,而且不易维护 使用HTML模板可以很好的解决这一问题 使用FreeMarker构建邮件模板,首先加入FreeMarker依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
public void sendHtmlMail(String from, String to, String subject, String content){
try{
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
javaMailSender.send(message);
}catch (MessagingException e){
System.out.println("发送失败!");
}
}
resources目录下创建mailtemplate.ft1作为邮件模板:
<div>邮箱激活</div>
<div>您的注册信息是:
<table border="1">
<tr>
<td>用户名</td>
<td>${username}</td>
</tr>
<tr>
<td>用户性别</td>
<td>${gender}</td>
</tr>
</table>
</div>
<div>
<a href="http://www.baidu.com">核对无误请点击本链接激活邮箱</a>
</div>
User实体类
public class User {
private String username;
private String gender;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
//测试
@Test
public void sendHtmlMail(){
try{
Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
ClassLoader loader = DemoApplicationTests.class.getClassLoader();
configuration.setClassLoaderForTemplateLoading(loader,"ft1");
Template template = configuration.getTemplate("mailtemplate.ft1");
StringWriter mail = new StringWriter();
User user = new User();
user.setUsername("测试用户");
user.setGender("男");
template.process(user, mail);
mailService.sendHtmlMail("xxxx@qq.com",
"xxx@163.com",
"测试邮件主题(FreeMarker)",
mail.toString());
}catch (Exception e){
e.printStackTrace();
}
}
使用Thymeleaf构建邮件模板
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Thymeleaf邮件模板默认位置是在resources/templates目录下
创建相应目录,然后创建邮件模板mailtemplate.html:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>邮件</title>
</head>
<body>
<div>邮箱激活</div>
<div>您的注册信息是:
<table border="1">
<tr>
<td>用户名</td>
<td th:text="${username}"></td>
</tr>
<tr>
<td>用户性别</td>
<td th:text="${gender}"></td>
</tr>
</table>
</div>
<div>
<a href="http:www.baidu.com">核对无误清点击本链接激活邮箱</a>
</div>
</body>
测试
@Autowired
TemplateEngine templateEngine;
@Test
public void sendHtmlMailThymeleaf(){
Context ctx = new Context();
ctx.setVariable("username", "tom");
ctx.setVariable("gender", "男");
String mail = templateEngine.process("mailtemplate.html", ctx);
mailService.sendHtmlMail("xxxx@qq.com",
"xxxx@163.com",
"测试邮件主题(Thymeleaf)",
mail);
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


