SpringBoot发送邮件

1.引入email依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2.开通邮箱相关的账户设置 //用授权码作为用户密码发送邮件

3.application.properties配置属性

spring.mail.password=授权码
spring.mail.username=xxxxxxx@qq.com
spring.mail.host=smtp.qq.com

4.配置JavaMailSender实例,发送邮件

@RunWith(SpringRunner.class)
@SpringBootTest
public class TaskApplicationTests {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String mymail;

    @Test
    public void contextLoads() throws Exception{
       /*
       //发生简单消息
       SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(mymail);
        message.setTo("3123213@qq.com");
        message.setSubject("白瑞新测试");
        message.setText("无聊的");
        mailSender.send(message);
*/
       //发送包含多媒体邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
        messageHelper.addAttachment("礼物.pdf", new File("C:\\Users\\dell\\Desktop\\剑指Offer.pdf"));
        messageHelper.setFrom(mymail);
        messageHelper.setTo("12345678@qq.com");
        messageHelper.setSubject("礼物");
        messageHelper.setText("<b style='clolr:red'>哈哈</b>",true);
        mailSender.send(mimeMessage);
    }
}
posted @ 2019-01-22 18:36  brx_blog  阅读(196)  评论(0编辑  收藏  举报