导入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
如果是使用QQ发送邮件,需要先获取一个授权码。首先进入QQ邮箱->设置->账户->开启服务
然后就获取到这个授权码了
配置
在application.properties中配置
#邮箱账户
spring.mail.username=123456@qq.com
#授权码
spring.mail.password=你的授权码
#主机
spring.mail.host=smtp.qq.com
#开启加密认证
spring.mail.properties.mail.smtp.ssl.enable=true
在test中测试:
package com.lyr;
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.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@SpringBootTest
class SpringbootOtherApplicationTests {
@Autowired
JavaMailSender mailSender;
@Test
void contextLoads() {
//一个普通的邮件
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("叮叮叮"); //邮件标题
mailMessage.setText("这是我用Spring Boot发的邮件,嘻嘻!"); //邮件内容
mailMessage.setTo("1234567@qq.com"); //接收人
mailMessage.setFrom("7654321@qq.com"); //发送人
mailSender.send(mailMessage);
}
@Test
void contextLoads2() throws MessagingException {
//一个复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
//组装
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//正文
helper.setSubject("叮叮叮");
helper.setText("这是我用Spring Boot发的邮件,嘻嘻!");
//附件
helper.addAttachment("sign.jpg",new File("C:\\Users\\ASUS\\Pictures\\Camera Roll\\sign.jpg"));
helper.setTo("1234567@qq.com");
helper.setFrom("7654321@qq.com");
mailSender.send(mimeMessage);
}
}
在test中运行就可以发送了。