一、首先到QQ邮箱申请开启POP3、SMTP协议
二、安装依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.3.23</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
三、配置文件
spring:#配置邮箱发送邮件mail:default-encoding: utf-8 #默认编码host: smtp.qq.com #配置SMTP 服务器地址username: xxxxxxx@qq.com #发送者邮箱password: xxxxxxxxxxx#申请到的授权码port: 587 #端口号587或 465properties: #配置SSL 加密工厂mail:smtp:socketFactoryClass: javax.net.ssl.SSLSocketFactorydebug: true #表示开启debug模式,这样,邮件发送的过程会在控制台打印出来,这样方便排查错误#配置这些好后,springboot会自动帮我们配置好相关的邮件发送类thymeleaf:cache: falseprefix: classpath:/templates/
四、如果需要发送模板的邮件,则在/templates/目录下建立email.html文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>使用Thymeleaf作为邮件的模板</title>
</head>
<body>
<p>hello 欢迎加入 xxx 大家庭,您的入职信息如下:</p>
<table border="1"><tr><td>姓名</td><td th:text="${username}"></td></tr><tr><td>职位</td><td th:text="${position}"></td></tr><tr><td>薪水</td><td th:text="${salary}"></td></tr>
</table>
<div style="color: #ff1a0e">一起努力创造辉煌</div></body>
</html>
五、如果需要异常打印信息的话新建自定义异常类BusinessException
public class BusinessException extends RuntimeException {public BusinessException(String msg){super(msg);}
}
六、如果需要发送附件的话,则新建网络文件转流类
package com.example.answer_system.utils;import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;//文件转换工具
public class FileUtils {/*** 将网络文件转换为文件流* @param imageUrl* @return*/public static MultipartFile fileUrlConvertToMultipartFile(String imageUrl) {try {// 将在线图片地址转换为URL对象URL url = new URL(imageUrl);// 打开URL连接URLConnection connection = url.openConnection();// 转换为HttpURLConnection对象HttpURLConnection httpURLConnection = (HttpURLConnection) connection;// 获取输入流InputStream inputStream = httpURLConnection.getInputStream();// 读取输入流中的数据,并保存到字节数组中ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int bytesRead;while ((bytesRead = inputStream.read(buffer)) != -1) {byteArrayOutputStream.write(buffer, 0, bytesRead);}// 将字节数组转换为字节数组byte[] bytes = byteArrayOutputStream.toByteArray();// 创建ByteArrayInputStream对象,将字节数组传递给它ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);// 创建MultipartFile对象,将ByteArrayInputStream对象作为构造函数的参数MultipartFile multipartFile = new MockMultipartFile("file", "filename.jpg", "image/jpg", byteArrayInputStream);return multipartFile;}catch (IOException ex){ex.printStackTrace();throw new BusinessException("附件无效");}}
}
七、测试方法
package com.example.answer_system.service.impl;import com.example.answer_system.service.IMailService;
import com.example.answer_system.utils.BusinessException;
import com.example.answer_system.utils.FileUtils;
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.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;@Service
public class MailServiceImpl implements IMailService {@Resourcepublic JavaMailSender javaMailSender;@Value("${spring.mail.username}")private String sendUserMailName;@Resourceprivate TemplateEngine templateEngine;//简单文本@Overridepublic String sendMailQQMsg(){SimpleMailMessage message=new SimpleMailMessage();//构建一个邮件对象message.setSubject("使用springboot发送邮件测试");//设置邮件主题message.setFrom(sendUserMailName);//设置邮件发送人,要与application.yml文件配置一致message.setTo(sendUserMailName);//设置收件人,如果有多个接收人,使用","隔开//message.setCc("3121624188@qq.com");//设置抄送人,可以有多个//message.setBcc("3121624188@qq.com");//设置隐秘抄送人,可以有多个message.setSentDate(new Date());//设置发送日期message.setText("小程使用springboot发送邮件的简单测试!!");//设置邮件正文javaMailSender.send(message);//发送邮件return "OK";}@Overridepublic String sendAttachFileMail(String filePath) {try {MimeMessage mimeMessage=javaMailSender.createMimeMessage();MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);//true表示构建一个带附件的邮件对象helper.setSubject("这是一封测试邮件,带附件的");helper.setFrom(sendUserMailName);helper.setTo(new String[]{sendUserMailName});helper.setSentDate(new Date());helper.setText("小程使用springboot发送可以带附件的邮件 测试!!");helper.addAttachment("james.jpg", FileUtils.fileUrlConvertToMultipartFile(filePath));//第一个参数是自定义的名称,第二个参数是文件的位置javaMailSender.send(mimeMessage);}catch (MessagingException ex){throw new BusinessException("发送异常");}catch (Exception ex){ex.printStackTrace();}finally {return "OK";}}@Overridepublic String sendThymeleaf(){try {MimeMessage mimeMessage = javaMailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);helper.setSubject("使用Thymeleaf模板作为发送邮件的模板");helper.setFrom(sendUserMailName);helper.setTo(sendUserMailName);helper.setSentDate(new Date());//这里进入的是Template的ContextContext context = new Context();//设置模板中的变量context.setVariable("username","程婷");context.setVariable("position","java开发工程师");context.setVariable("salary","XXXXXK");//第一个参数作为模板的,名称String process = templateEngine.process("email.html", context);//第二个参数true表示这是html文本helper.setText(process,true);javaMailSender.send(mimeMessage);}catch (MessagingException ex){throw new BusinessException("失败");}return "OK";}}