假设从qq邮箱发一封邮件到163邮箱,大致步骤如下
这个过程设计到了很多个协议
具体使用(以qq邮箱为例)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
复制代码
# smtp服务器地址 spring.mail.host=smtp.qq.com # 协议类型 spring.mail.protocol=smtp spring.mail.username=发件邮箱 # 授权码 spring.mail.password=使用发件邮箱生成的授权码 spring.mail.default-encoding=UTF-8 spring.mail.port=465 # 加密工具 spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory spring.mail.properties.mail.debug=true 复制代码
@Autowired
MailSender mailSender;
@Test
public void contextLoads() {
SimpleMailMessage msg = new SimpleMailMessage();
//收件人
msg.setTo("收件人邮箱");
//邮件主题
msg.setSubject("这是一封测试邮件");
//发件人
msg.setFrom("发件人邮箱");
//邮件内容
msg.setText("hello mail!");
mailSender.send(msg);
}
复制代码