步骤
第一步
在pom.xml中导入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
第二步
在测试类中代码如下
@RunWith(SpringRunner.class)
@SpringBootTest
public class StartApplicationTests {
@Autowired
JavaMailSender mailSender;
@Test
public void contextLoads() throws Exception{
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setText("<b style=‘color:red;’>zouqianyu so beautiful </b>",true);
helper.setSubject("Happy birthday");
helper.setTo("zqy_poppy@163.com");
helper.setFrom("zqy_poppy@163.com");
helper.addAttachment("1.jpg",new File("C:\\Users\\Administrator\\Pictures\\1.jpg"));
helper.addAttachment("2.jpg",new File("C:\\Users\\Administrator\\Pictures\\2.jpg"));
mailSender.send(mimeMessage);
}
}
第三步
在application.properties中
spring.mail.username=你的用户名
spring.mail.password=163邮箱设置的授权码
spring.mail.host=smtp.163.com
spring.mail.properties.mail.smtp.ssl.enable=true
效果
坑点
1.javax.mail.AuthenticationFailedException: 550
我使用的是163的邮箱,由于没有开通pop/stmp协议导致出现这个异常,
邮箱设置里开通这两个协议即可。