邮件任务
邮件发送,在我们的日常开发中,也非常的多,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>
看它引入的依赖,可以看到 jakarta.mail
<dependency><groupId>com.sun.mail</groupId><artifactId>jakarta.mail</artifactId><version>1.6.4</version><scope>compile</scope>
</dependency>
2、查看自动配置类:MailSenderAutoConfiguration
这个类中存在bean,JavaMailSenderImpl
然后我们去看下配置文件
@ConfigurationProperties(prefix = "spring.mail"
)
public class MailProperties {private static final Charset DEFAULT_CHARSET;private String host;private Integer port;private String username;private String password;private String protocol = "smtp";private Charset defaultEncoding;private Map<String, String> properties;private String jndiName;
}
3、配置文件:
spring.mail.username=24736743@qq.com
spring.mail.password=你的qq授权码
spring.mail.host=smtp.qq.com
# qq需要配置ssl
spring.mail.properties.mail.smtp.ssl.enable=true
获取授权码:在QQ邮箱中的设置->账户->开启pop3和smtp服务
4、Spring单元测试
@Autowired
JavaMailSenderImpl mailSender;@Test
public void contextLoads() {//邮件设置1:一个简单的邮件SimpleMailMessage message = new SimpleMailMessage();message.setSubject("通知-明天来狂神这听课");message.setText("今晚7:30开会");message.setTo("24736743@qq.com");message.setFrom("24736743@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("24736743@qq.com");helper.setFrom("24736743@qq.com");mailSender.send(mimeMessage);
}
查看邮箱,邮件接收成功!
我们只需要使用Thymeleaf进行前后端结合即可开发自己网站邮件收发功能了!
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-L5BSFhog-1610187548376)(C:\Users\王东梁\AppData\Roaming\Typora\typora-user-images\image-20210109181809891.png)]