本文共 2552 字,大约阅读时间需要 8 分钟。
在项目中添加必要的依赖关系:
org.springframework.boot spring-boot-starter-mail
在application.properties中添加以下配置:
# 网易邮箱配置spring.mail.username=xxxxxx@163.comspring.mail.password=网易账号授权码spring.mail.host=smtp.163.com# 注意:使用qq邮箱时,需在配置中添加以下内容:spring.mail.properties.mail.smtp.ssl.enable=true
登录网易云邮箱,进入“设置” > “邮件客户端设置” > “安全中心” > “获取授权码”并开启IMAP/SMTP服务,获取授权码以完成邮箱配置。
在测试类中注入JavaMailSender:
@Autowiredprivate JavaMailSender mailSender;
@Testpublic void contextLoads() { SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); simpleMailMessage.setSubject("主题"); simpleMailMessage.setText("邮件内容"); simpleMailMessage.setTo("收件人邮箱"); simpleMailMessage.setFrom("发件人邮箱"); mailSender.send(simpleMailMessage);} @Testpublic void contextLoads2() throws MessagingException { MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setSubject("主题"); helper.setText("支持HTML样式", true); helper.addAttachment("1.jpg", new File("C:\\Users\\lenovo\\Desktop\\1.jpg")); helper.setTo("收件人邮箱"); helper.setFrom("发件人邮箱"); mailSender.send(mimeMessage);} 在主程序中添加注解:
@EnableAsync@SpringBootApplicationpublic class Springboot11TestApplication { public static void main(String[] args) { SpringApplication.run(Springboot11TestApplication.class, args); }} @Servicepublic class AsyncService { @Async public void hello() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("数据正在处理中"); }} 在主配置类中添加注解:
@EnableScheduling@SpringBootApplicationpublic class Springboot11TestApplication { public static void main(String[] args) { SpringApplication.run(Springboot11TestApplication.class, args); }} @Servicepublic class ScheduledService { @Scheduled(cron = "50 30 15 * * ?") // 每天的0秒任何时候都 public void hello() { System.out.println("hello,你被执行了"); }} cron表达式是用空格分隔的字段,每个字段代表不同的时间单位,具体含义如下:
以下是常见的cron表达式示例:
0/2 * * * * ?
0 0/2 * * * ?
0 2 1 * * ?
0 15 10 ? * MON-FRI
0 15 10 ? 6L 2002-2006
0 15 10 ? * 6#3
通过合理设计cron表达式,可以根据具体需求定时触发业务逻辑。
转载地址:http://qfsm.baihongyu.com/