定時發送郵件

定時發送郵件

背景

甲方爸爸:新接入業務在國慶以及軍運會期間須要天天巡檢業務併發送郵件告知具體狀況!
我司:沒問題。
甲方爸爸:假期也要發噢。
我司:沒問題(。。。)。
html

剛開始計劃指定幾個同事輪流發送,業務只要不被攻擊通常是沒有問題的。可是想想休息日還要處理工做上的事情(非緊急的)就不爽,近幾年一直在作前端的事情,後臺碰的少,畢竟也接觸過,因此決定搞一個定時發送郵件的程序,遂上網查找資料。前端

郵件類選擇

在網上大體上看了下,目前有兩種方案:java

  1. MimeMessage
String title = createTitle();
        String text = createText();
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.qq.com");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props, 
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {        
                 return new PasswordAuthentication(from, passwd);
                }
            });
        MimeMessage message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(title);
            message.setText(text);
            System.out.println(text);
            Transport.send(message);
        } catch(Exception e) {
        	e.printStackTrace();
        }
複製代碼
  1. SimpleMail
mail.setHostName(host);
		mail.setAuthentication(user, passwd);
		mail.setFrom(user);
		mail.setCharset("UTF-8");
		mail.setSubject(title);
		mail.setSSLOnConnect(true);
		mail.setMsg(content);
		mail.addTo(to);
		mail.send();
複製代碼

在本地重構代碼並進行了測試,都是正常發送和接收,我的以爲SimpleMail看起來更加簡潔,因此郵件類就選它了服務器

定時器

網上搜索一大堆,具體就不一一介紹了,我用的是Quartz Quartz 設計有三個核心類,分別是微信

  • Scheduler 調度器 調度器就至關於一個容器,裝載着任務和觸發器。該類是一個接口,表明一個 Quartz 的獨立運行容器, TriggerJobDetail 能夠註冊到 Scheduler 中, 二者在 Scheduler 中擁有各自的組及名稱, 組及名稱是 Scheduler 查找定位容器中某一對象的依據, Trigger 的組及名稱必須惟一, JobDetail 的組和名稱也必須惟一(但能夠和 Trigger 的組和名稱相同,由於它們是不一樣類型的)。Scheduler 定義了多個接口方法, 容許外部經過組及名稱訪問和控制容器中 TriggerJobDetail
  • Job任務 定義須要執行的任務。該類是一個接口,只定義一個方法 execute(JobExecutionContext context),在實現類的 execute 方法中編寫所須要定時執行的 Job(任務), JobExecutionContext 類提供了調度應用的一些信息。Job 運行時的信息保存在 JobDataMap 實例中
  • Trigger 觸發器 負責設置調度策略。該類是一個接口,描述觸發 job 執行的時間觸發規則。主要有 SimpleTriggerCronTrigger 這兩個子類。當且僅當需調度一次或者以固定時間間隔週期執行調度,SimpleTrigger 是最適合的選擇;而 CronTrigger 則能夠經過 Cron 表達式定義出各類複雜時間規則的調度方案:如工做日週一到週五的 15:00~16:00 執行調度等

開發測試

發送者郵箱必須開啓客戶端POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務,具體能夠在郵箱設置頁進行設置,密碼使用受權碼session

  1. 建立SendMail類,將發送郵件邏輯代碼進行封裝
public class SendMail implements Job {

	private static String user = "11111111@qq.com";
	private static String passwd = "passwd";//受權碼
	private static String to = "22222@qq.com";
	private static String host = "smtp.qq.com";
	
	public static void sendMailForSmtp(String title, String content, String[] tos, String[] ccs) throws EmailException {
        SimpleEmail mail = new SimpleEmail();
		// 設置郵箱服務器信息
		mail.setHostName(host);
		// 設置密碼驗證器passwd爲受權碼
		mail.setAuthentication(user, passwd);
		// 設置郵件發送者
		mail.setFrom(user);
		// 設置郵件編碼
		mail.setCharset("UTF-8");
		// 設置郵件主題
		mail.setSubject(title);
		//SSL方式
		mail.setSSLOnConnect(true);
		// 設置郵件內容
// mail.setMsg(content);
		// 設置郵件接收者
// mail.addTo(to);
		mail.addTo(tos);
		mail.addCc(ccs);
		// 發送郵件
		MimeMultipart multipart = new MimeMultipart();
		//郵件正文 
        BodyPart contentPart = new MimeBodyPart();  
        try {
			contentPart.setContent(content, "text/html;charset=utf-8");
	        multipart.addBodyPart(contentPart);  
	        //郵件附件 
	        BodyPart attachmentPart = new MimeBodyPart();
	        File file = new File("C:\\lutong\\20190918002.log");
	        FileDataSource source = new FileDataSource(file);  
	        attachmentPart.setDataHandler(new DataHandler(source));  
			attachmentPart.setFileName(MimeUtility.encodeWord(file.getName()));
			multipart.addBodyPart(attachmentPart);
			mail.setContent(multipart);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
        System.out.println(JsonUtil.toJson(mail));
        mail.send();
		System.out.println("mail send success!");
    }
    @Override
	public void execute(JobExecutionContext var1) throws JobExecutionException {
		// TODO Auto-generated method stub
		//多個接收者
		String[] tos = {"11111@qq.com","2222@qq.com"};
		//多個抄送者
		String[] ccs = {"33333@qq.com","44444@qq.com"};
		try {
			SendMail.sendMailForSmtp("title", "hello <br> ccy", tos, ccs);
		} catch (EmailException e) {
			e.printStackTrace();
		}
	}
}
複製代碼
  1. 建立CronTrigger,定時發送任務
public class CronTrigger {
	public static void main(String[] args){
		//初始化job
		JobDetail job = JobBuilder.newJob(SendMail.class)// 建立 jobDetail 實例,綁定 Job 實現類
				.withIdentity("ccy", "group1")//指明job名稱、所在組名稱
				.build();
		//定義規則
		 Trigger trigger = TriggerBuilder
		 .newTrigger()
		 .withIdentity("ccy", "group1")//triggel名稱、組
		 .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))//每隔5s執行
		 .build();
		Scheduler scheduler = null;
		try {
			scheduler = new StdSchedulerFactory().getScheduler();
			System.out.println("start job...");
			//把做業和觸發器註冊到任務調度中
			scheduler.scheduleJob(job, trigger);
			//啓動
			scheduler.start();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
}
複製代碼

測試結果

mail.png

後記

技術溝通羣歡迎加入 併發

weixinqun_1.png
若是對筆者感興趣也歡迎你加我好友一塊兒討論技術,誇誇白 本人微信 gm4118679254
相關文章
相關標籤/搜索