1. 在Spring Boot的工程中的pom.xml
中引入spring-boot-starter-mail
依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2. 在完成了依赖引入之后,只需要在application.properties
中配置相应的属性内容。
下面我们以QQ邮箱为例,在application.properties
中加入如下配置
用户名就是qq邮箱名、密码是POP3/SMTP服务授权码,QQ邮箱POP3/SMTP服务开启详见开启smtp服务
如果使用腾讯企业邮箱host=smtp.exmail.qq.com,用户名是企业邮箱名,密码是企业邮箱密码:
#spring.mail.host=smtp.qq.com
#spring.mail.username=5461111@qq.com
#spring.mail.password=zgbfeb1111
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
#端口使用默认端口为最好
3. 编写测试代码
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EnableAutoConfiguration
public class ApplicationTests {
@Autowired
private JavaMailSender mailSender;
@Test
public void sendSimpleMail() throws Exception {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("li@qq.com");//properties中配置的username
message.setTo("5468@qq.com");//向谁发送
message.setSubject("主题:简单邮件");
message.setText("简单邮件内容from ");
mailSender.send(message);
}