java实现qq邮箱每天定时发送邮件

1 import org.quartz.Job;
2 import org.quartz.JobExecutionContext;
3 import org.quartz.JobExecutionException;
4 import java.util.Calendar;
5 import java.text.SimpleDateFormat;
6 import java.util.Date;
7 import java.lang.InterruptedException;
8 import java.util.Random;
9 import java.util.Properties;
10 import javax.mail.*;
11 import javax.mail.internet.*;
12 public class MailJob implements Job
13 {
14     public void execute(JobExecutionContext context)
15         throws JobExecutionException {
16         //收件人,标题和文本内容
17         String to = "#######@126.com";//填写你要发给谁
18         String title = createTitle();
19         String text = createText();
20         //设置属性
21         Properties props = new Properties();
22         //QQ邮箱发件的服务器和端口
23         props.put("mail.smtp.host", "smtp.qq.com");
24         props.put("mail.smtp.socketFactory.port", "465");
25         props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
26         props.put("mail.smtp.auth", "true");
27         props.put("mail.smtp.port", "25");
28         Session session = Session.getDefaultInstance(props, 
29             new javax.mail.Authenticator() {
30                 protected PasswordAuthentication getPasswordAuthentication() {        
31                     //填写你的qq邮箱用户名和密码        
32                  return new PasswordAuthentication("*******@qq.com", "###***%%%");
33                 }
34             });
35         MimeMessage message = new MimeMessage(session);
36         //这里用flag来标记是否发件成功(有时候会连不上服务器),
37         //如果没有,继续发送,直到发送成功为止。
38         int flag = 0;
39         {
40         try {
41         //设置发件人,收件人,主题和文本内容,并发送
42             message.setFrom(new InternetAddress("*******@qq.com"));//填写你自己的qq邮箱,和上面相同
43             message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
44             message.setSubject(title);
45             message.setText(text);
46             System.out.println("Preparing sending mail...");
47             System.out.println(text);
48             Transport.send(message);
49             flag = 1;
50             System.out.println("message sent successfully");
51         } catch(Exception e) {
52             flag = 0;
53         }
54         } while(flag == 0);
55     }
56     //下面的两个方法,用来随机组合标题和文本内容。文本内容由四部分随机组合。
57     //产生标题
58     public String createTitle() {
59         String[] titles = {"love", "I love you", "Miss you", "My baby"};    
60         Random randT = new Random(System.currentTimeMillis());
61         String title = titles[randT.nextInt(titles.length)];
62         return title;
63     }
64     //产生文本内容,文本内容由四部分随机组合得到。
65     public String createText() {
66         //名字纯属虚构,如有雷同(肯定会有),纯属巧合。
67         String[] parts1 = {"晓静,你好。", "晓静,你还好吗?", "晓静,你那边天气怎么样?"};
68         String[] parts2 = {
69             "距离上次见面,我感觉已经好长时间了。",
70             "流去的时间磨不去我对你的爱。",
71             "我仍然记得你在天安门前的那一抹笑容。"
72         };
73         String[] parts3 = {"今天,我大胆地追求你。",
74              "我不怕大胆地对你说,我爱你。",
75              "此刻,月亮代表我的心。"
76         };
77         String[] parts4 = {
78             "未来,我的心依旧属于你。",
79             "好想在未来陪你一起慢慢变老,当然在我心中你不会老。"
80         };
81         Random randT = new Random(System.currentTimeMillis());
82         String text = parts1[randT.nextInt(parts1.length)]
83             + parts2[randT.nextInt(parts2.length)]
84             + parts3[randT.nextInt(parts3.length)]
85             + parts4[randT.nextInt(parts4.length)];
86         return text;
87     }
88     
89 }
复制代码
触发器的代码:

复制代码
1 import org.quartz.CronScheduleBuilder;
2 import org.quartz.JobBuilder;
3 import org.quartz.JobDetail;
4 import org.quartz.Scheduler;
5 import org.quartz.Trigger;
6 import org.quartz.TriggerBuilder;
7 import org.quartz.impl.StdSchedulerFactory;
8 import java.util.Random;
9 public class CronTriggerExample 
10 {
11     public static void main( String[] args ) throws Exception
12     {
13           //创建工作对象
14         JobDetail job = JobBuilder.newJob(MailJob.class)
15         .withIdentity("dummyJobName", "group1").build();
16         //为了立即测试,可以使用下面的代码,每隔5秒钟执行一次
17         //int secDelta = 5;
18          //Trigger trigger = TriggerBuilder
19         // .newTrigger()
20         // .withIdentity("dummyTriggerName", "group1")
21         // .withSchedule(
22         //     CronScheduleBuilder.cronSchedule("0/" + secDelta + " * * * * ?"))
23         // .build();
24         //在每天早上的9点多(不超过3分钟)执行
25         Random rand = new Random(System.currentTimeMillis());
26         int secDelta = rand.nextInt(60 * 3);
27         //创建触发器对象
28          Trigger trigger = TriggerBuilder
29         .newTrigger()
30         .withIdentity("dummyTriggerName", "group1")
31         .withSchedule(
32             CronScheduleBuilder.cronSchedule(secDelta + " 0 9 ? * SUN-SAT"))
33         .build();
34         
35         Scheduler scheduler = new StdSchedulerFactory().getScheduler();
36         scheduler.start();
37         //将触发器与工作关联起来
38         scheduler.scheduleJob(job, trigger);  
39     }
40 }
发邮件依赖的包:activation.jar,mail.jar
quartz下载地址:http://www.quartz-scheduler.org/downloads/

将发邮件依赖的包和quartz下载得到的lib路径下的jar包全部放在mylib路径下,mylib路径与java文件位于同一个目录。编译和运行时,可以使用命令:

set classpath=mylib/*;.;
javac CronTriggerExample.java
java CronTriggerExample

更多Java学习资料可关注:gzitcast

发布了782 篇原创文章 · 获赞 3 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/u010395024/article/details/104937378