#引入依赖
在Spring Boot中发送邮件,需要用到spring-boot-starter-mail,引入spring-boot-starter-mail:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
#邮件配置
在application.yml中进行简单的配置(使用网易163邮箱):
server:
port: 80
spring:
mail:
host: smtp.163.com
username: 账号
password: 第三方授权登录密码
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
#发送简单的邮件
编写EmailController,注入JavaMailSender:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/email")
public class EmailController {
@Autowired
private JavaMailSender jms;
@Value("${spring.mail.username}")
private String from;
@RequestMapping("sendSimpleEmail")
public String sendSimpleEmail() {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo("668899@163.com"); // 接收地址
message.setSubject("普通邮件"); // 标题
message.setText("普通邮件内容。"); // 内容
jms.send(message);
return "success";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
测试访问http://localhost/email/sendSimpleEmail
#发送HTML格式的邮件
EmailController,SimpleMailMessage替换为MimeMessage:
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/email")
public class EmailController {
@Autowired
private JavaMailSender jms;
@Value("${spring.mail.username}")
private String from;
@RequestMapping("sendHtmlEmail")
public String sendHtmlEmail() {
MimeMessage message = null;
try {
message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo("668899@163.com"); // 接收地址
helper.setSubject("HTML格式的邮件"); // 标题
// 带HTML格式的内容
StringBuffer sb = new StringBuffer("<p style='color:#6db33f'>HTML格式邮件的内容。</p>");
helper.setText(sb.toString(), true);
jms.send(message);
return "success";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
helper.setText(sb.toString(), true);中的true表示发送HTML格式邮件。启动项目,测试访问http://localhost/email/sendHtmlEmail,提示"success",可看到文本已经加上了颜色#6db33f:
#发送带附件的邮件
发送带附件的邮件和普通邮件相比,其实就只是多了个传入附件的过程。不过使用的仍是MimeMessage:
package com.springboot.demo.controller;
import java.io.File;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/email")
public class EmailController {
@Autowired
private JavaMailSender jms;
@Value("${spring.mail.username}")
private String from;
@RequestMapping("sendAttachmentsMail")
public String sendAttachmentsMail() {
MimeMessage message = null;
try {
message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo("668899@163.com"); // 接收地址
helper.setSubject("带附件的邮件"); // 标题
helper.setText("详情参见附件内容!"); // 内容
// 传入附件
FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/file/测试.docx"));
helper.addAttachment("测试.docx", file);
jms.send(message);
return "success";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
测试访问http://localhost/email/sendAttachmentsMail,提示“success”:
#发送带静态资源的邮件
发送带静态资源的邮件其实就是在发送HTML邮件的基础上嵌入静态资源(比如图片),嵌入静态资源的过程和传入附件类似,唯一的区别在于需要标识资源的cid:
package com.springboot.demo.controller;
import java.io.File;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/email")
public class EmailController {
@Autowired
private JavaMailSender jms;
@Value("${spring.mail.username}")
private String from;
@RequestMapping("sendInlineMail")
public String sendInlineMail() {
MimeMessage message = null;
try {
message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo("668899@163.com"); // 接收地址
helper.setSubject("带静态资源的邮件"); // 标题
helper.setText("<html><body>图片:<img src='cid:img'/></body></html>", true); // 内容
// 传入附件
FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/img/mv.png"));
helper.addInline("img", file);
jms.send(message);
return "success";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
helper.addInline("img", file);中的img和图片标签里cid后的名称相对应。启动项目访问http://localhost/email/sendInlineMail,提示"success":
#使用模板发送邮件
在发送验证码等情况下可以创建一个邮件的模板,唯一的变量为验证码。这个例子中使用的模板解析引擎为Thymeleaf,所以首先引入Thymeleaf依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在template目录下创建一个emailTemplate.html模板:
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>验证码</title>
</head>
<body>
您好,您的验证码为{code},五分钟内有效。
</body>
</html>
发送模板邮件,本质上还是发送HTML邮件,只不过多了绑定变量的过程:
ackage com.springboot.demo.controller;
import java.io.File;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
@RestController
@RequestMapping("/email")
public class EmailController {
@Autowired
private JavaMailSender jms;
@Value("${spring.mail.username}")
private String from;
@Autowired
private TemplateEngine templateEngine;
@RequestMapping("sendTemplateEmail")
public String sendTemplateEmail(String code) {
MimeMessage message = null;
try {
message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo("668899@163.com"); // 接收地址
helper.setSubject("邮件摸板测试"); // 标题
// 处理邮件模板
Context context = new Context();
context.setVariable("code", code);
String template = templateEngine.process("emailTemplate", context);
helper.setText(template, true);
jms.send(message);
return "success";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
其中code对应模板里的${code}变量。启动项目,访问http://localhost/email/sendTemplateEmail?code=QW58,提示"success":
原文参考:https://mrbird.cc/Spring-Boot-Email.html