最近看到定时任务和邮件发送,闲来无事就尝试了一下java
须要在pom文件中加入邮件依赖spring
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
须要进行基本配置安全
password密码不是登陆密码,须要到邮箱里查看受权码服务器
houst是服务地址我这里是QQ邮箱因此是QQ服务器函数
spring.mail.properties.mail.smtp.ssl.enable=true开启安全连接
spring.mail.username=104*******64@qq.com spring.mail.password=vxsefzdipoqybcgd spring.mail.host=smtp.qq.com spring.mail.properties.mail.smtp.ssl.enable=true
两个注解:
@EnableScheduling、@Scheduled
cron表达式:
字段 容许值 容许的特殊字符
秒 0-59 , - * /
分 0-59 , - * /
小时 0-23 , - * /
日期 1-31 , - * ? / L W C
月份 1-12 , - * /
星期 0-7或SUN-SAT 0,7是SUN , - * ? / L C #
特殊字符 表明含义
, 枚举
- 区间
* 任意
/ 步长
? 日/星期冲突匹配
L 最后
W 工做日
C 和calendar联系后计算过的值
# 星期,4#2,第2个星期四
注入邮件发送器
JavaMailSenderImpl mailSender;
简单邮件发送
SimpleMailMessage mailMessage = new SimpleMailMessage();
复杂的消息邮件
MimeMessage mimeMessage=mailSender.createMimeMessage();
package com.lty.spring.task.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.io.File; import java.io.UnsupportedEncodingException; @Service public class ScheduleService { @Autowired JavaMailSenderImpl mailSender; //@Scheduled定时任务注解cron是对任务开始的时间进行设置 秒 分 时 日 月 每周的周几 @Scheduled(cron = "* * * * * *")//每一秒发送一封 public void hello()throws Exception{ String from="104********64@qq.com"; //建立一个复杂的消息邮件 MimeMessage mimeMessage=mailSender.createMimeMessage(); MimeMessageHelper helper=new MimeMessageHelper(mimeMessage, true);//邮件设置 helper.setSubject("开会通知"); helper.setText("<b style='color:red'>今天晚上在大厅开会,请接收到的同志回复信息。未回复的将辞退。</b>", true);//如果不写true则HTML标签不执行 //收件人的邮箱 helper.setTo("178*******89@qq.com"); //设置自定义发件人昵称 String nick=""; try { nick=javax.mail.internet.MimeUtility.encodeText("中国电力总局"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
//发件人的地址 helper.setFrom(new InternetAddress(nick+" <"+from+">"));//上传文件 helper.addAttachment("1.jpg",new File("C:\\Users\\Administrator\\Desktop\\photo\\1.jpg")); helper.addAttachment("2.jpg",new File("C:\\Users\\Administrator\\Desktop\\photo\\2.jpg")); mailSender.send(mimeMessage); } }
在主函数中须要加上@ENableScheduling注解做用是开启注解的定时任务spring-boot
@EnableScheduling @SpringBootApplication public class Springboot04TaskApplication { public static void main(String[] args) { SpringApplication.run(Springboot04TaskApplication.class, args); } }
建议定时设置不要像我同样,否则会有不少,虽然能够一键阅读但仍是有些费事spa