Quartz入门(四) --Quartz与Spring结合:定时发送邮件

Quartz入门(四) --Quartz与Spring结合:定时发送邮件

使用Spring项目的Quartz定时任务可以在xml中配置,即写一个Job类来做定时任务实际要完成的任务,但定时功能交给xml文件来配置。

Example:要定时发送邮件

  • 那要写一个Job类来实现发送邮件的任务
  • 任务的触发交给xml文件来配置
  • 最后将此xml文件加入到Spring的applicationContext.xml中就可以啦
发送邮件任务

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

/**
 * Created by CiCi on 2017/5/9.
 * 发邮件任务
 */
public class SendEmailJob {
    private static final Logger LOGGER = LoggerFactory.getLogger(SendEmailJob.class);

    EmailInformation emailInformation;
    RedPackageToExcel redPackageToExcelInstance;
    public RedPackageToExcel getRedPackageToExcelInstance() {
        return redPackageToExcelInstance;
    }

    public void setRedPackageToExcelInstance(RedPackageToExcel redPackageToExcelInstance) {
        this.redPackageToExcelInstance = redPackageToExcelInstance;
    }

    public EmailInformation getEmailInformation() {
        return emailInformation;
    }

    public void setEmailInformation(EmailInformation emailInformation) {
        this.emailInformation = emailInformation;
    }

    public void sendMail() {
        try
        {
            final String filePath = emailInformation.getRedPackageAttachLoc() + emailInformation.getAttachName() + ".xlsx";
            String fromMail = emailInformation.getFromMail();
            String toMail = emailInformation.getToMail();
            String user = emailInformation.getUser();
            String password = emailInformation.getPassword();
            String mailTitle = emailInformation.getMailTitle();
            String mailContent = emailInformation.getMailContent();
            String attachName = emailInformation.getAttachName();

            //加载一个配置文件
            Properties props = new Properties();

            // smtp:简单邮件传输协议
            // 设置邮件服务器主机名
            props.put("mail.smtp.host", "smtp.163.com");

            //发送服务器需要通过验证
            props.put("mail.smtp.auth", "true");

            //设置环境信息
            Session session = Session.getInstance(props);//根据属性新建一个邮件会话
            session.setDebug(true); //会打印一些调试信息。

            //由邮件会话新建一个消息对象
            MimeMessage message = new MimeMessage(session);

            //设置邮件内容
            message.setFrom(new InternetAddress(fromMail));//设置发件人的地址
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail));//设置收件人,并设置其接收类型为TO
            message.setSubject(mailTitle);//设置标题
            //设置信件内容

            //因为需要加载附件,需要装载多个主体部件
            MimeMultipart partList = new MimeMultipart("mixed");
            message.setContent(partList);

            //创建一个部件
            MimeBodyPart part1 = new MimeBodyPart();
            part1.setText(mailContent);
            partList.addBodyPart(part1);

            //再创建一个部件
            MimeBodyPart part2 = new MimeBodyPart();

            //将原有的export.xlsx删除,重新生成export.xlsx文件并发送
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            }

            // 添加附件的内容
            DataSource source = new FileDataSource(filePath);
            part2.setDataHandler(new DataHandler(source));

            //指定附件的名字,使用MimeUtility.encode()对中文进行编码
            SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
            String address = simpleFormat.format(new Date());
            part2.setFileName(MimeUtility.encodeText(attachName + address +".xlsx")); //设置的这个新的名字一定要带有后缀格式啊.xlsx!!!

            partList.addBodyPart(part2);

            //发送邮件
            Transport transport = session.getTransport("smtp");
            transport.connect(user, password);
            transport.sendMessage(message, message.getAllRecipients());//发送邮件,其中第二个参数是所有已设好的收件人地址
            transport.close(); //这个最好放到finally中哎
        }catch (Exception e) {
            LOGGER.error("sendEmail failed" + e);
        }
    }

    public void execute(){
        try {
            sendMail();
        } catch (Exception e) {
            LOGGER.error("autosendEmail failed" + e);
        }

    }
}

XMLl文件配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


    <!--定时发送邮件-->
    <bean id="sendEmailJob" class="com.xiaomi.cashpay.statistics.autosendstatistics.SendEmail.SendEmailJob"></bean>
    <bean id="job" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="sendEmailJob" />
        <property name="targetMethod" value="execute" />
    </bean>

    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail" ref="job" />
        <!--<property name="cronExpression" value="0 0 9 * * ?" />-->
        <property name="cronExpression" value="0 * * * * ?" />
    </bean>

    <bean id="scheduler" lazy-init="false" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="cronTrigger" />
            </list>
        </property>
        <property name="autoStartup" value="true" />
    </bean>
</beans>
将quartz-config.xml文件引入到applicationContext.xml中

<import resource="classpath*:/quartz-config.xml" />

酱紫就可以了~ 定时发送邮件新技能Get~

That's all. Thank U~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容