引入maven依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application.properties(163邮箱)
#####163邮箱########
spring.mail.host=smtp.163.com
spring.mail.username=*****@163.com
#163邮箱密码
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
qq邮箱
qq邮箱对应的是验证码,不是密码
######qq邮箱########
spring.mail.host=smtp.qq.com
spring.mail.username=******@qq.com
#QQ邮箱授权码
spring.mail.password=xuojxtkdojvzbhjj
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
运行类
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.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class BikeApplicationTests {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String username;
@Test
public void testSendSimple() {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(username);
message.setTo("***@qq.com");
message.setSubject("标题:测试标题");
message.setText("测试内容部份");
javaMailSender.send(message);
}
}
常见问题
1.发送邮件535错误
问题是因为配置文件中配置的邮箱密码是登录密码而不是安全密码导致的,直接将密码修改成安全密码就可以了(163邮箱在开启smtp服务时会要求输入安全密码的)
2.554错误
引发次问题是因为此邮件触发了163邮箱服务器反垃圾规则具体原因在错误上已经提示了,到这里查看即可