Quartz + javamail + Spring 定时发送邮件

1、java类编写

Mail.java

package cn.mail.domain;
import java.util.List;
/**
 * 邮件接收人实体类
 */
public class Mail {
    private String title;
    private String content;
    private List<String> toAddress;
    private List<String> toCCAddress;
    // get & set
    public String getTitle() {return title;}
    public void setTitle(String title) {this.title = title;}
    public String getContent() {return content;}
    public void setContent(String content) {this.content = content;}
    public List<String> getToAddress() {return toAddress;}
    public void setToAddress(List<String> toAddress) {this.toAddress = toAddress;}
    public List<String> getToCCAddress() {return toCCAddress;}
    public void setToCCAddress(List<String> toCCAddress) {this.toCCAddress = toCCAddress;}
}
MailSmtp.java
package cn.mail.domain;
/**
 * 邮件发件人实体类
 */
public class MailSmtp {
    private String host;
    private String loginName;
    private String password;
    private String fromAddress;
    // get & set
    public String getHost() {return host;}
    public void setHost(String host) {this.host = host;}
    public String getLoginName() {return loginName;}
    public void setLoginName(String loginName) {this.loginName = loginName;}
    public String getPassword() {return password;}
    public void setPassword(String password) {this.password = password;}
    public String getFromAddress() {return fromAddress;}
    public void setFromAddress(String fromAddress) {this.fromAddress = fromAddress;}
}
MailDao.java

package cn.mail.dao;
import cn.mail.domain.Mail;
/**
 * 邮件Dao层
 */
public interface MailDao {
    public static final String SERVICE_NAME = "cn.mail.dao.impl.MailDaoImpl";
    public String sendMailMessage(Mail mail) throws Exception;
    public String sendMailMessage(Mail mail, String type) throws Exception;
}
MailDaoImpl.java
package cn.mail.dao.impl;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Repository;
import net.sf.json.JSONObject;
import cn.mail.dao.MailDao;
import cn.mail.domain.Mail;
import cn.mail.domain.MailSmtp;

@Repository(value=MailDao.SERVICE_NAME)
public class MailDaoImpl implements MailDao {
    private Logger logger = Logger.getLogger(MailDaoImpl.class);
    @Override
    public String sendMailMessage(Mail mail) throws Exception {
        return sendMail(mail, "text");
    }
    @Override
    public String sendMailMessage(Mail mail, String type) throws Exception {
        return sendMail(mail, type);
    }
    private String sendMail(Mail mail, String type){
        logger.info("-----开始发送邮件-----");
        ApplicationContext ac = new ClassPathXmlApplicationContext("mail_beans.xml");
        MailSmtp smtp = ac.getBean(MailSmtp.class);
        
        JSONObject json = new JSONObject();
        String flag = "send-success";
        String msg = "Send mail successed";
        
        Properties props = new Properties();
        props.setProperty("mail.smtp.host", smtp.getHost());
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        
        Session session = Session.getInstance(props);
//		session.setDebug(true);

        Message message = new MimeMessage(session);
        try {
            // 设置邮件主题
            message.setSubject(mail.getTitle());
            // 设置邮件发送人
            message.setFrom(new InternetAddress(smtp.getFromAddress()));
            message.setSentDate(new Date());
            
            if(type.equals("html")){
                String mailEnd = "<hr style='width: 350px; height: 1px;' color='#b5c4df' size='1' align='left'>"
                + "<div style='color:gray;font-size:14px;'>"
                + "<strong style='font-size:16px;'>muycode</strong> &nbsp;&nbsp;Company&nbsp;&nbsp;Department"
                + "<br>手机:186-****-****   &nbsp;&nbsp;邮箱:358075228@qq.com"
                + "<br>Address  "
                + "<br>网址:www.muycode.com"
                + "<br><p style='font-size:12px;'>如果您对邮件有什么疑问,请随时与我联系,谢谢!</p>"
                + "</div>";
                message.setContent(mail.getContent() + mailEnd, "text/html;charset=utf-8");
            }else{
                // 设置邮件内容 -- text格式
                message.setText(mail.getContent());
            }
            
            // 设置邮件接收人
            List<String> toMail = mail.getToAddress();
            Address[] toAddr = new InternetAddress[toMail.size()];
                if(toAddr.length > 0){
                    for (int i = 0; i < toAddr.length; i++) {
                        toAddr[i] = new InternetAddress(toMail.get(i));
                    }
                }else{
                flag = "send-error";
                msg = "The address is empty for send mail";
                json.element("flag", flag);
                json.element("msg", msg);
                logger.error("收件人为空~~~");
                return json.toString();
            }
            message.setRecipients(RecipientType.TO, toAddr);
            // 设置邮件抄送人
            List<String> toCCMail = mail.getToCCAddress();
            if(null != toCCMail && toCCMail.size() > 0){
                Address[] toCCAddr = new InternetAddress[toCCMail.size()];
                for (int i = 0; i < toCCAddr.length; i++) {
                    toCCAddr[i] = new InternetAddress(toCCMail.get(i));
                }
                message.setRecipients(RecipientType.CC, toCCAddr);
            }
            
            Transport trans = session.getTransport();
            trans.connect(smtp.getLoginName(), smtp.getPassword());
            trans.sendMessage(message, message.getAllRecipients());
            trans.close();
        } catch (MessagingException e) {
            e.printStackTrace();
            flag = "send-error";
            msg = e.getMessage();
            logger.error("出现异常:"+e.getMessage());
        }
        logger.info("-----邮件发送成功-----");
        json.element("flag", flag);
        json.element("msg", msg);
        return json.toString();
    }
}

SendMailJob.java

package cn.quartz.jobs;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import cn.mail.dao.MailDao;
import cn.mail.dao.impl.MailDaoImpl;
import cn.mail.domain.Mail;
/**
 * 发送邮件
 */
public class SendMailJob {
    /**
    * 每分钟发送一次邮件
    */
    public void SendMailMessageForOne(){
        Mail mail = new Mail();
        mail.setTitle("定时邮件");
        mail.setContent("<h4>现在时间为:</h4>" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) 
        + "<p style='color:red;'>注意:该邮件为1分钟发送一次,如果我没有停止程序的话~~~<p>"
        + "<p style='color:blue;'>-----这是一封以html格式发送并且带有小尾巴的邮件-----</p>");
        List<String> toMail = new ArrayList<String>();
        toMail.add("358075228@qq.com");
        mail.setToAddress(toMail);
        
        List<String> toCCMail = new ArrayList<String>();
        toCCMail.add("");
        mail.setToCCAddress(toCCMail);
        MailDao mailDao = new MailDaoImpl();
        String result;
        try {
            result = mailDao.sendMailMessage(mail,"html");
            System.out.println("result:"+result);
        } catch (Exception e) {
            System.out.println("SendMailJob出现异常:"+e.getMessage());
            e.printStackTrace();
        }
    }
}
TestQuartz.java

package cn.mail.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestQuartz {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("quartz_beans.xml");
    }
}

2、配置文件

beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
    <import resource="classpath:mail_beans.xml"/>
    <import resource="classpath:quartz_beans.xml"/>
</beans>
log4j.properties

log4j.rootLogger = INFO,A,B,C

# Console
log4j.appender.A = org.apache.log4j.ConsoleAppender
log4j.appender.A.Target = System.out
log4j.appender.A.layout = org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern = %p %t %c - %m%n

# log
log4j.appender.B = org.apache.log4j.DailyRollingFileAppender
log4j.appender.B.File = WebRoot/WEB-INF/log/log.log
log4j.appender.B.Append = true
log4j.appender.B.Threshold = INFO 
log4j.appender.B.layout = org.apache.log4j.PatternLayout
log4j.appender.B.layout.ConversionPattern = %p %t %c - %m%n

# exception error
log4j.appender.C = org.apache.log4j.DailyRollingFileAppender
log4j.appender.C.File = WebRoot/WEB-INF/log/error.log
log4j.appender.C.Append = true
log4j.appender.C.Threshold = ERROR 
log4j.appender.C.layout = org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern =%p %t %c - %m%n
mail_beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.1.xsd">
        
    <!-- 配置注解的自动扫描范围 -->
    <context:component-scan base-package="cn.mail"/>
    <!-- 引入配置文件 -->
    <context:property-placeholder location="classpath:smtp.properties"/>
    
    <bean id="mailsmtp" class="cn.mail.domain.MailSmtp">
        <property name="host" value="${host}"/>
        <property name="loginName" value="${loginName}"/>
        <property name="password" value="${password}"/>
        <property name="fromAddress" value="${fromAddress}"/>
    </bean>
</beans>
quartz_beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
    
    <bean id="sendMailJob" class="cn.quartz.jobs.SendMailJob"></bean>
        <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="name" value="job_name"></property>
        <property name="group" value="job_group"></property>
        <property name="concurrent" value="false"></property>
        <property name="targetObject" ref="sendMailJob"></property>
        <property name="targetMethod" value="SendMailMessageForOne"></property>
    </bean>

    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="name" value="cron_name"></property>
        <property name="group" value="cron_group"></property>
        <property name="jobDetail" ref="jobDetail"></property>
        <property name="cronExpression" value="0 0/1 * * * ?"></property>
    </bean>
    
    <bean id="shcedul" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="jobDetails" ref="jobDetail"></property>
        <property name="triggers" ref="cronTrigger"></property>
    </bean>
</beans>
smtp.properties

host=smtp.163.com
loginName=******@163.com
password=******
fromAddress=******@163.com

源码链接:http://pan.baidu.com/s/1o8KyTAy 密码:zquz

发表评论

Blue Captcha Image
Refresh

*