@Test
public void test3() throws MessagingException {
sendMail(true, "测试封装方法",
"<h1 style=\"color:red\"> 测试内容 </h1>",
"1234567@qq.com",
"1234567@qq.com",
"utf-8",
"C:\\1.jpg",
"C:\\2.jpg");
}
/**
* 发送邮件
*
* @param html 是否支持解析HTML标签
* @param subject 设置邮件标题
* @param text 文本内容
* @param setTo 发件人
* @param setFrom 收件人
* @param encoding 字符集编码(默认为utf-8)
* @param filepath 附件文件路径
* @throws MessagingException 一般为文件路径错误
*/
public void sendMail(Boolean html, String subject, String text, String setTo, String setFrom, String encoding, String... filepath) throws MessagingException {
if (encoding == null || "".equals(encoding)) {
encoding = "utf-8";
}
// 一个复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
// 组装
// multipart:是否支持多文件
// Encoding;字符集编码格式
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, encoding);
//设置主题
helper.setSubject(subject);
//text:文本内容
//html:是否支持解析html标签
helper.setText(text, html);
//附件
for (int i = 0; i < filepath.length; i++) {
File file = new File(filepath[i]);
helper.addAttachment(file.getName(), file);
}
//发件人
helper.setTo(setTo);
//收件人
helper.setFrom(setFrom);
mailSender.send(mimeMessage);
}
配置文件
spring.mail.username=you@qq.com
spring.mail.password=password
spring.mail.host=smtp.qq.com
# 开启加密验证,QQ邮箱必须要有这一条,其他的邮箱不需要
spring.mail.properties.mail.smtl.ssl.enable=true
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>