springboot如何发邮件
springboot发送邮件,首先需要开启邮箱的POP3/SMTP服务权限(qq为例),登陆qq邮箱,点击设置,点击账户,点击开启POP3/SMTP服务权限服务,会获取一个序列码值,需要在配置文件中填写。
springboot中引入依赖包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<!-- web应用所需html模版-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在springboot配置文件中,配置邮箱信息:
spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=邮箱名称
spring.mail.password=开启服务获取的值
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;
// 自定义,html模版,包含图片,附件
public void sendAllMail(String from, String to,String cc,
String subject, String content,String[] srcPath,String[] resIds, File file){
try {
MimeMessage message=javaMailSender.createMimeMessage();
MimeMessageHelper helper=new MimeMessageHelper(message,true);
helper.setFrom(from);//发送者
helper.setTo(to);//接收者
helper.setCc(cc);//抄送者
helper.setSubject(subject);//主题
//邮件内容,设置为true表示内容以html形式传输
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);
}
//发送附件
helper.addAttachment(file.getName(),file);
javaMailSender.send(message);
} catch (MessagingException e) {
System.out.println("发送失败");
}
}
}
这里使用了springboot的thymeleaf模版来发送邮件。模版html代码如下(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><img src='cid:p01' /></div>
</div>
</body>
</html>
测试邮件是否可以发送成功。创建controller类,编写发送邮件方法如下:
@PostMapping("/sendAllMail")
public void sendAllMail(){
Context context=new Context();
context.setVariable("username","sui");
context.setVariable("gender","男");
String mail=templateEngine.process("mailtemplate.html",context);
mailService.sendAllMail("发送者",
"接收者",
"抄送者",
"邮件主题",
mail,
new String[]{"图片地址"},
new String[]{"p01"},//图片名称
new File("发送文件路径"));
}
访问该方法测试邮件是否发送即可!