SpringBoot发简单邮件的正确姿势
程序员文章站
2022-06-16 08:46:39
...
0)背景:用springboot发简单的邮件
1)代码如下
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
applicaton.properties
spring.mail.host=smtp.qq.com
spring.mail.username=aaa@qq.com
spring.mail.password=你的授权码
spring.mail.default-encoding=UTF-8
spring.mail.port=587
spring.mail.properties.mail.debug=true
spring.mail.properties.mail.stmp.socketFactory.class=javax.net.ssl.SSLSocketFactory
Controller
@RestController
public class QQMailController {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
String from;
@GetMapping("/a")
public void a() {
System.out.println(">>>>>>>>>>>>>" + from);
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setTo("aaa@qq.com");// 发给谁
simpleMailMessage.setCc(from);//抄送给谁
simpleMailMessage.setSubject("测试邮件的主题");// 邮件主题
simpleMailMessage.setText("测试邮件的内容内容asdfasdfasdfasdf!!!!");// 内容
simpleMailMessage.setFrom(from);//谁发(必须写application.properties文件里面配置的spring.mail.username)
simpleMailMessage.setSentDate(new Date());//发送时间
javaMailSender.send(simpleMailMessage);
}
}