利用Spring Boot发送邮件,以163邮箱为例
1.添加Maven包依赖,在pom.xml文件中添加如下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency
2.在application.properties文件中添加如下代码
spring.mail.host=smtp.163.com
spring.mail.username=***@163.com
spring.mail.password=***
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
注意spring_mail_password那里的密码是授权密码,而不是登陆密码,授权密码在邮箱设置,pop3/smtp处可以设置
3.测试代码
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("163")
public class My163MailTest {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String username;
@Test
public void testSendSimple() {
SimpleMailMessage message = new SimpleMailMessage();
// message.setFrom(username);
message.setFrom("***@163.com");//发送邮箱,也就是你的邮箱,或者可用上面的代码直接获取
message.setTo("###@qq.com");
message.setSubject("love");
message.setText("你好");
javaMailSender.send(message);
}
}
注意点:此处连接163邮箱发送邮件,有时回报554 DT:SPM错误,这是网易的反垃圾机制
网易邮箱错误码详情:企业退信的常见问题?-163邮箱常见问题
个人经验:主题,内容不要包含Test,测试等字眼
当天申请的授权码,当天使用该邮箱会一直报这个错误,这点要注意!