一、导入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId>
</dependency>
二、添加配置
application.yml文件
将username修改为自己的邮箱,password修改为自己的邮箱授权码(下面有QQ授权码的生成地址)
spring:mail:port: 465username: xxxxxx@qq.com # 自己的邮箱或者发送人的邮箱password: xxxxxx # 邮箱授权码host: smtp.qq.com properties:mail:smtp:auth: falsessl:enable: truedebug: true
QQ授权码 生成地址: 账号与安全 (qq.com)
三、导入工具类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
@Component
public class SendEmailUtil {
/*** 消息发送工具*/@Autowiredprivate JavaMailSender sender;
/*** @param senderEmail 发送者的邮箱* @param receiverEmail 接收者的邮箱* @param messageText 消息内容*/public void send(String senderEmail, String receiverEmail, String messageText) {// 创建消息对象SimpleMailMessage message = new SimpleMailMessage();
//设置消息相关信息// 发送者邮箱message.setFrom(senderEmail);// 消息内容message.setText(messageText);// 接收者邮箱message.setTo(receiverEmail);
// 发送消息sender.send(message);}
/*** @param senderEmail 发送者的邮箱* @param receiverEmail 接收者的邮箱* @param messageText 消息内容* @param subject 消息主题*/public void send(String senderEmail, String receiverEmail, String messageText,String subject) {// 创建消息对象SimpleMailMessage message = new SimpleMailMessage();
//设置消息相关信息// 发送者message.setFrom(senderEmail);// 消息主题message.setSubject(subject);// 消息内容message.setText(messageText);// 接收者message.setTo(receiverEmail);
// 发送消息sender.send(message);}
}
四、发送消息
在SpringBoot的测试类中发送
@Autowired
private SendEmailUtil sendEmailUtil;@Test
void sendUtil() {String senderEmail = "xxxxxx@qq.com"; // 发送者邮箱String receiverEmail = "xxxxxx@qq.com"; // 接收者邮箱String msg = "hello,编程大师!"; // 消息内容String subject = "测试springboot发送邮箱"; // 消息主题sendEmailUtil.send(senderEmail,receiverEmail,msg,subject);
}
邮箱查看消息
如: