springboot邮件任务

邮件发送,在我们的日常开发中,也非常的多,Springboot也帮我们做了支持

  • 邮件发送需要引入spring-boot-start-mail

  • SpringBoot 自动配置MailSenderAutoConfiguration

  • 定义MailProperties内容,配置在application.yml中

  • 自动装配JavaMailSender

  • 测试邮件发送

1.pom依赖

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

2.配置文件

# MailProperties
spring.mail.host=smtp.sina.com
spring.mail.port=465
spring.mail.username=*******@sina.com
spring.mail.password=*****
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.ssl.enable=true

3.新浪邮箱开启pop3和SMTP服务

4.测试

@Autowired
JavaMailSenderImpl mailSender;

@Test
public void contextLoads() {
   //邮件设置1:一个简单的邮件
   SimpleMailMessage message = new SimpleMailMessage();
   message.setSubject("通知");
   message.setText("今晚7:30开会");

   message.setTo("123123@qq.com");
   message.setFrom("3536743@qq.com");
   mailSender.send(message);
}

@Test
public void contextLoads2() throws MessagingException {
   //邮件设置2:一个复杂的邮件
   MimeMessage mimeMessage = mailSender.createMimeMessage();
   MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

   helper.setSubject("通知");
   helper.setText("<b style='color:red'>今天 7:30来开会</b>",true);

   //发送附件
   helper.addAttachment("1.jpg",new File(""));
   helper.addAttachment("2.jpg",new File(""));

   helper.setTo("123456789@qq.com");
   helper.setFrom("123456@qq.com");

   mailSender.send(mimeMessage);
}

 

 

上一篇:基于SpringBoot集成所有邮件发送功能


下一篇:Laravel常用包