Spring,Quartz和JavaMail集成教程

Quartz是一個作業調度框架,用于調度要在指定的時間表上執行的作業。JavaMail是一個用于從Java應用程序發送/接收電子郵件的API。

Spring具有集成點,可以集成Quartz和JavaMail,從而使這些API易于使用。 讓我們創建一個小型演示應用程序,以展示如何集成Spring + Quartz + JavaMail。

我們的應用程序是每天早上6點向朋友發送生日祝福電子郵件。

Email.java

package com.sivalabs.reminders;import java.util.ArrayList;
import java.util.List;public class Email
{private String from;private String[] to;private String[] cc;private String[] bcc;private String subject;private String text;private String mimeType;private List<Attachment> attachments = new ArrayList<Attachment>();public String getFrom(){return from;}public void setFrom(String from){this.from = from;}public String[] getTo(){return to;}public void setTo(String... to){this.to = to;}public String[] getCc(){return cc;}public void setCc(String... cc){this.cc = cc;}public String[] getBcc(){return bcc;}public void setBcc(String... bcc){this.bcc = bcc;}public String getSubject(){return subject;}public void setSubject(String subject){this.subject = subject;}public String getText(){return text;}public void setText(String text){this.text = text;}public String getMimeType(){return mimeType;}public void setMimeType(String mimeType){this.mimeType = mimeType;}public List<Attachment> getAttachments(){return attachments;}public void addAttachments(List<Attachment> attachments){this.attachments.addAll(attachments);}public void addAttachment(Attachment attachment){this.attachments.add(attachment);}public void removeAttachment(int index){this.attachments.remove(index);}public void removeAllAttachments(){this.attachments.clear();}
}

Attachment.java

package com.sivalabs.reminders;public class Attachment
{private byte[] data;private String filename;private String mimeType;private boolean inline;public Attachment(){}public Attachment(byte[] data, String filename, String mimeType){this.data = data;this.filename = filename;this.mimeType = mimeType;}public Attachment(byte[] data, String filename, String mimeType, boolean inline){this.data = data;this.filename = filename;this.mimeType = mimeType;this.inline = inline;}public byte[] getData(){return data;}public void setData(byte[] data){this.data = data;}public String getFilename(){return filename;}public void setFilename(String filename){this.filename = filename;}public String getMimeType(){return mimeType;}public void setMimeType(String mimeType){this.mimeType = mimeType;}public boolean isInline(){return inline;}public void setInline(boolean inline){this.inline = inline;}}

EmailService.java

package com.sivalabs.reminders;import java.util.List;import javax.activation.DataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;public class EmailService
{private JavaMailSenderImpl mailSender = null;public void setMailSender(JavaMailSenderImpl mailSender){this.mailSender = mailSender;}public void sendEmail(Email email) throws MessagingException {MimeMessage mimeMessage = mailSender.createMimeMessage();// use the true flag to indicate you need a multipart messageboolean hasAttachments = (email.getAttachments()!=null &&email.getAttachments().size() > 0 );MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, hasAttachments);helper.setTo(email.getTo());helper.setFrom(email.getFrom());helper.setSubject(email.getSubject());helper.setText(email.getText(), true);List<Attachment> attachments = email.getAttachments();if(attachments != null && attachments.size() > 0){for (Attachment attachment : attachments){String filename = attachment.getFilename() ;DataSource dataSource = new ByteArrayDataSource(attachment.getData(),attachment.getMimeType());if(attachment.isInline()){helper.addInline(filename, dataSource);}else{helper.addAttachment(filename, dataSource);}}}mailSender.send(mimeMessage);}
}

BirthdayWisherJob.java

package com.sivalabs.reminders;import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;import javax.mail.MessagingException;import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.QuartzJobBean;public class BirthdayWisherJob extends QuartzJobBean
{private EmailService emailService;public void setEmailService(EmailService emailService){this.emailService = emailService;}@Overrideprotected void executeInternal(JobExecutionContext context) throws JobExecutionException{System.out.println("Sending Birthday Wishes... ");List<User> usersBornToday = getUsersBornToday();for (User user : usersBornToday){try{Email email = new Email();email.setFrom("admin@sivalabs.com");email.setSubject("Happy BirthDay");email.setTo(user.getEmail());email.setText("<h1>Dear "+user.getName()+",Many Many Happy Returns of the day :-)</h1>");byte[] data = null;ClassPathResource img = new ClassPathResource("HBD.gif");InputStream inputStream = img.getInputStream();data = new byte[inputStream.available()];while((inputStream.read(data)!=-1));Attachment attachment = new Attachment(data, "HappyBirthDay","image/gif", true);email.addAttachment(attachment);emailService.sendEmail(email);}catch (MessagingException e){e.printStackTrace();}catch (Exception e){e.printStackTrace();}}}private List<User> getUsersBornToday(){List<User> users = new ArrayList<User>();User user1 = new User("Siva Prasad", "sivaprasadreddy.k@gmail.com", new Date());users.add(user1);User user2 = new User("John", "abcd@gmail.com", new Date());users.add(user2);return users;}
}

applicationContext.xml

<beans><bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"><property name="triggers"><list><ref bean="birthdayWisherCronTrigger" /></list></property></bean><bean id="birthdayWisherCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"><property name="jobDetail" ref="birthdayWisherJob" /><!-- run every morning at 6 AM --><property name="cronExpression" value="0/5 * * * * ?" /></bean><bean name="birthdayWisherJob" class="org.springframework.scheduling.quartz.JobDetailBean"><property name="jobClass" value="com.sivalabs.reminders.BirthdayWisherJob" /><property name="jobDataAsMap"><map><entry key="emailService" value-ref="emailService"></entry></map></property></bean><bean id="emailService" class="com.sivalabs.reminders.EmailService"><property name="mailSender" ref="mailSender"></property></bean><bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"><property name="defaultEncoding" value="UTF-8"/><property name="host" value="smtp.gmail.com" /><property name="port" value="465" /><property name="protocol" value="smtps" /><property name="username" value="admin@gmail.com"/><property name="password" value="*****"/><property name="javaMailProperties"><props><prop key="mail.smtps.auth">true</prop><prop key="mail.smtps.starttls.enable">true</prop><prop key="mail.smtps.debug">true</prop></props></property></bean></beans>

TestClient.java

package com.sivalabs.reminders;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestClient {public static void main(String[] args){ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); }}

參考:我的JCG合作伙伴 Siva的“ Spring + Quartz + JavaMail集成教程” ,在My Experiments on Technology博客上 。

相關文章 :
  • 使用Spring使用Java發送電子郵件– GMail SMTP服務器示例
  • Spring MVC開發–快速教程
  • GWT 2 Spring 3 JPA 2 Hibernate 3.5教程
  • Spring MVC3 Hibernate CRUD示例應用程序

翻譯自: https://www.javacodegeeks.com/2011/06/spring-quartz-javamail-tutorial.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/374694.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/374694.shtml
英文地址,請注明出處:http://en.pswp.cn/news/374694.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Java_Web三大框架之Hibernate操作數據庫(三)

使用Hibernate操作數據庫需要七個步驟&#xff1a;&#xff08;1&#xff09;讀取并解析配置文件Configuration conf newConfiguration().configure(); &#xff08;2&#xff09;讀取并解析映射信息&#xff0c;創建SessionFactorySessionFactory sf conf.buildSessionFacto…

android布局1

第二類&#xff1a;屬性值必須為id的引用名“id/id-name” 僅RelativeLayout中有效 android:layout_below 在某元素的下方 android:layout_above 在某元素的的上方 android:layout_toLeftOf 在某元素的左邊 android:layout_toRightOf 在某元素的右…

Spring MVC開發–快速教程

這是我們的JCG合作伙伴之一&#xff0c;來自Manoj的有關使用Spring開發Web應用程序的簡短教程&#xff0c; 網址為“ The Khangaonkar Report ”。 &#xff08;注意&#xff1a;對原始帖子進行了少量編輯以提高可讀性&#xff09; Spring MVC使用基于模型視圖控制器體系結構&…

spring mvc controller間跳轉 重定向 傳參

url&#xff1a;http://zghbwjl.blog.163.com/blog/static/12033667220137795252845/ 1. 需求背景 需求&#xff1a;spring MVC框架controller間跳轉&#xff0c;需重定向。有幾種情況&#xff1a;不帶參數跳轉&#xff0c;帶參數拼接url形式跳轉&#xff0c;帶參數不拼接參…

尋找數組的中心索引

給你一個整數數組 nums &#xff0c;請計算數組的 中心下標 。 數組 中心下標 是數組的一個下標&#xff0c;其左側所有元素相加的和等于右側所有元素相加的和。 如果中心下標位于數組最左端&#xff0c;那么左側數之和視為 0 &#xff0c;因為在下標的左側不存在元素。這一點…

STL sector 應用

1 #include <iostream>2 #include <string>3 #include <vector>4 #include <cstdio>5 using namespace std;6 int n;7 vector<int> pile[30];8 9 //找到a所在pile和height&#xff0c;以應用的形式返回調用者&#xff0c; 10 void find_block(in…

將Jersey與Spring整合

Spring提供了很多好處&#xff0c;并通過其依賴項注入機制&#xff0c;應用程序生命周期管理和Hibernate支持&#xff08;僅舉幾例&#xff09;促進了最佳實踐。 另外&#xff0c;當您想擁有干凈的類似于REST的服務器端JSON Api時&#xff0c;我發現Jersey非常方便。 本文簡要介…

JAVAWEB 生成excel文字在一格顯示兩位不變成#號

在用java生成excel的時候會發現這種問題&#xff0c; 如果是人家給的模板還好&#xff0c;如果不是模板&#xff0c;而是通過代碼生成的話&#xff0c; 就需要進行處理了&#xff0c; 一個小單元格&#xff0c;如果是一位的話&#xff0c;如1-9顯示沒有問題&#xff0c;一旦是兩…

力扣面試題 01.07. 旋轉矩陣

給你一幅由 N N 矩陣表示的圖像&#xff0c;其中每個像素的大小為 4 字節。請你設計一種算法&#xff0c;將圖像旋轉 90 度。 不占用額外內存空間能否做到&#xff1f; 代碼一 思路&#xff1a;對于矩陣中第 ii 行的第 jj 個元素&#xff0c;在旋轉后&#xff0c;它出現在倒數…

依賴注入–手動方式

依賴注入是一種將行為與依賴解決方案分開的技術。 用簡單的話來說&#xff0c;它允許開發人員定義具有特定功能的類&#xff0c;這些功能取決于各種協作者&#xff0c;而不必定義如何獲取對這些協作者的引用。 以此方式&#xff0c;實現了各個組件之間的解耦&#xff0c;并且通…

一個疏忽引發的思考!(strerror)

前幾天寫代碼因為自己的疏忽導致一遍又一遍的Segmentation fault (core dumped)。該問題是因為strerror&#xff08;errno&#xff09;返回的指針指向非法的內存導致程序打印錯誤時崩潰。 嘗試數次無果&#xff0c;為了進度。簡單粗暴的換成了perror(str)。今天忙里偷閑&#x…

力扣面試題 01.08. 零矩陣

編寫一種算法&#xff0c;若M N矩陣中某個元素為0&#xff0c;則將其所在的行與列清零 代碼一思路&#xff1a; 第一次遍歷時記錄&#xff0c;用兩個布爾類型數組標記行和列中是否有0元素&#xff1b; 第二次遍歷時置零 class Solution {public void setZeroes(int[][] matr…

Java最佳實踐–字符串性能和精確字符串匹配

在使用Java編程語言時&#xff0c;我們將繼續討論與建議的實踐有關的系列文章&#xff0c;我們將討論String性能調優。 我們將專注于如何有效地處理字符串創建&#xff0c; 字符串更改和字符串匹配操作。 此外&#xff0c;我們將提供我們自己的用于精確字符串匹配的最常用算法的…

mac下開發環境常用操作與命令

【1】 修改hosts文件 vim /private/etc/hosts轉載于:https://www.cnblogs.com/zsmynl/p/4714492.html

keil里面填數據

編譯后寄存器和堆棧的內存數據可以直接寫進去的。 寄存器&#xff0c;雙擊就可以&#xff0c;注意里面是十六進制 堆棧&#xff0c;也是十六進制&#xff0c;八位的 00 00 00 00 &#xff0c;但這個是從右到左的&#xff0c;比如0x00000006 應該填 06 00 00 00 把數據取出來 取…

力扣498. 對角線遍歷

給你一個大小為 m x n 的矩陣 mat &#xff0c;請以對角線遍歷的順序&#xff0c;用一個數組返回這個矩陣中的所有元素。 代碼思路&#xff1a;以第一行和右邊最后一列作為每輪的開始元素&#xff0c;先用temp存儲&#xff0c;全部按 從左上到右下 的順序遍歷&#xff0c;但是…

調試生產服務器– Eclipse和JBoss展示

您是否編寫有錯誤的代碼&#xff1f; 不&#xff0c;當然不。 對于我們其余的確實會編寫帶有錯誤的代碼的凡人&#xff0c;我想解決一個非常敏感的問題&#xff1a;調試在生產服務器上運行的應用程序。 因此&#xff0c;您的應用程序已準備好進行部署。 單元測試全部成功&…

ubuntu server獲取并自動設置最快鏡像的方法

一&#xff0c;安裝方法1 add-apt-repository ppa:ossug-hychen/getfastmirrorapt-get install getfastmirror 如果添加了臨時源&#xff0c;這樣移除add-apt-repository --remove ppa:ossug-hychen/getfastmirror 二&#xff0c;安裝方法2 wget -O getfastmirror-master.zip h…

linux之x86裁剪移植---ffmpeg的H264解碼顯示(420、422)

在虛擬機上yuv420可以正常顯示 &#xff0c;而945&#xff08;D525&#xff09;模塊上卻無法顯示 &#xff0c;后來驗證了directdraw的yuv420也無法顯示 &#xff0c;由此懷疑顯卡不支持 &#xff0c;后把420轉換為422顯示。420顯示如下&#xff1a;/* 編譯命令&#xff1a;arm…

Spring依賴注入技術的發展

回顧Spring框架的歷史&#xff0c;您會發現實現依賴注入的方式在每個發行版中都在增加。 如果您使用該框架已經超過一個月&#xff0c;那么在這篇回顧性文章中可能不會發現任何有趣的東西。 除了Scala中的最后一個示例&#xff0c;沒有其他希望&#xff0c;這種語言在Spring中意…