SpringBoot实现邮件发送(QQ邮箱发送)

1.添加依赖


    org.springframework.boot
    spring-boot-starter-mail

2.开启POP3/SMTP服务,获取QQ邮箱授权码

3.然后直接在springboot配置文件中配置即可(可配哪些内容可参见MailSenderAutoConfiguration.java的-->MailProperties.class)

[email protected]
spring.mail.password=****************

#smtp.163.com、根据邮箱类型
spring.mail.host=smtp.qq.com

#开启加密验证(QQ独有)
spring.mail.properties.mail.smtp.ssl.enable=true

4.在junit测试中,注入mail的实现对象JavaMailSenderImpl,来实现发送

普通邮件

@Autowired
JavaMailSenderImpl mailSender;

@Test
void contextLoads() {
    //一个简单的邮件
    SimpleMailMessage mailMessage = new SimpleMailMessage();
    mailMessage.setSubject("RIP,KOBE");
    mailMessage.setText("湖人总冠军");
    mailMessage.setTo("[email protected]");
    mailMessage.setFrom("[email protected]");

    mailSender.send(mailMessage);
}

复杂邮件

@Autowired
JavaMailSenderImpl mailSender;

@Test
void contextLoads2() throws MessagingException {
    //复杂的邮件
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    //组装
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    //正文
    helper.setSubject("湖人总冠军");
    helper.setText("

RIP,KOBE

",true); //附件 helper.addAttachment("1.jpg", new File("C:\\Users\\asus\\Desktop\\1.jpg")); helper.addAttachment("2.jpg", new File("C:\\Users\\asus\\Desktop\\2.jpg")); //发送 helper.setTo("[email protected]"); helper.setFrom("[email protected]"); mailSender.send(mimeMessage); }

启动,即可发送成功,可将该操作封装成一个工具类,便于以后使用

写完后 /** 回车,会自动生成相关注释

 

你可能感兴趣的:(SpringBoot,学习笔记)