导入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.在properties配置邮箱
# 发件人QQ号
spring.mail.username=2508575653@qq.com
# QQ邮箱授权码
spring.mail.password=xxxxxxxxxxxxxxx
# 主机
spring.mail.host=smtp.qq.com
# qq邮箱需要开启安全连接
spring.mail.properties.mail.stmp.ssl.enable=true
3.获取QQ邮箱授权码
打开网页版的QQ邮箱,登录邮箱,进入设置-》帐户
然后,在“帐户”设置中,找到服务设置项,进行设置,如下:
开启POP3/SMTP服务器,验证密保
用正确的手机好发送正确的验证内容到指定的号码,成功获取授权码
测试代码
package com.peng;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@SpringBootTest
class SpringbootSecurityApplicationTests {@Autowiredprivate JavaMailSenderImpl javaMailSender;@Testvoid contextLoads() {//简单邮件SimpleMailMessage message = new SimpleMailMessage();message.setSubject("测试");//主题message.setText("邮箱内容");、//接受者邮箱(任何邮箱都可以)message.setTo("2508575653@qq.com");//发送者邮箱message.setFrom("2508575653@qq.com");javaMailSender.send(message);}@Testvoid test() throws MessagingException {//复杂邮件MimeMessage mimeMessage = javaMailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);//组装,开启之后可以添加附件helper.setSubject("ok");//主题helper.setText("内容");helper.addAttachment("按什么名称发送.后缀",new File("文件路径"));helper.setTo("收件人");helper.setFrom("发件人");javaMailSender.send(mimeMessage);}
}