手把手教你 ,spring定时发送邮件

我这里只是一个简单的例子,也是在网上找到的一个邮件发送的例子,然后自己修改成了quartz定时发送,下面有源代码大家可以下载,可以根据需要进行修改。

第一步:建立一个web Project

 

加入必须的包 到lib中  

    activation-1.1.jar

    mail-1.4.jar
    commons-collections-3.2.jar
    commons-lang-2.5.jar
    commons-logging-1.1.jar
    quartz-1.6.1.jar
    spring-2.5.jar
    spring-context-support-2.5.6.jar
    spring-web-2.5.6.jar
    velocity-1.6.4.jar

 最好不要用myeclipse自带的包,可能会有冲突。

 

 

第二步:配置web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  
   <listener>
	  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<context-param>
	  <param-name>contextConfigLocation</param-name>
	  <param-value>classpath:applicationContext.xml</param-value>
	 </context-param>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

我这里applicationContext.xml就直接放在了classpath下

文件目录如图:

 

手把手教你 ,spring定时发送邮件

第三步:加入所需要的配置文件

   applicationContext.xml   :

 

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
	xmlns:tx="http://www.springframework.org/schema/tx">
	
	<!-- 属性文件加载 -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				 <value>classpath:mail.properties</value>
				<!--<value>WEB-INF/mail.properties</value> -->
			</list>
		</property>
	</bean>

	<!-- 邮件发送器 -->
	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="host" value="${mail.host}" />
		<property name="username" value="${mail.username}" />
		<property name="password" value="${mail.password}" />
		<property name="defaultEncoding" value="UTF-8"></property>
		<property name="javaMailProperties">
			<props>
				<prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
				<prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
			</props>
		</property>
	</bean>
	<!--velocity模板引擎 -->
	<bean id="velocityEngine"
		class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
		<property name="resourceLoaderPath" value="classpath:velocity"></property>
	</bean>

	<bean id="mailUtil" class="com.ryt.mail.MailUtil">
		<property name="javaMailSender" ref="mailSender"></property>
		<property name="from" value="${mail.from}"></property>
		<property name="encoding" value="UTF-8"></property>
		<property name="templateLocation" value="hello.vm"></property>
		<property name="velocityEngine" ref="velocityEngine"></property>
		<property name="title" value="youTitle"></property>
	</bean>
   <!-- *****定时任务开始************************************************* -->
        <bean id="JobServiceImpl" class="com.ryt.mail.MailManager" >
       		 <property name="mailUtil" ref="mailUtil"></property>
        </bean>
        <!-- -->
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
            <bean class="org.springframework.scheduling.quartz.CronTriggerBean">
                    <property name="jobDetail">
                        <bean class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
                            <property name="targetObject" ref="JobServiceImpl" />
                            <property name="targetMethod" value="sendMail" />
                        </bean>
                    </property>
                    <property name="cronExpression" value="0 0 12 * * ?" />
                </bean>
            </list>
        </property>
    </bean>
    
</beans>

  

mail.properties   :

修改成你的邮箱吧,注意哦。邮箱设置里面要:开启POP3/SMTP服务 

如:qq邮箱-->邮箱设置-->账户-->POP3/IMAP/SMTP服务-->开启POP3/SMTP服务 

[email protected]
mail.host=smtp.qq.com
mail.password=youPassword
mail.smtp.auth=true
mail.smtp.timeout=25000
mail.username=youUserName

 

log4j.properties (根据你的需要添加,也 可以不要) :

log4j.rootLogger=info, A1,logfile  

#log4j.rootLogger=INFO,A1,R
# ConsoleAppender
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%F:%L] [%p] - %m%n
##logfile
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.File=${catalina.base}/logs/proj.log 
log4j.appender.logfile.DatePattern='_'yyyyMMdd'.log'
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%F:%L] [%p] - %m%n

 

第四步:编写邮件发送器

 

package com.ryt.mail;

import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineUtils;

/**
 * 邮件发送器
 */
public class MailUtil {

    protected final Log log = LogFactory.getLog(getClass());
    
    private JavaMailSender javaMailSender;
    private VelocityEngine velocityEngine;
    private String from;
    private String title;
    private String encoding;
    private String templateLocation;
    private String[] toEmails;
    private Map<String,String> model;

    public boolean send(){
        try {
			MimeMessage msg = javaMailSender.createMimeMessage();
			MimeMessageHelper message = new MimeMessageHelper(msg, true, "UTF-8");
            message.setFrom(from);
            message.setSubject(title);
            message.setTo(toEmails);
			message.setText(getMessage(), true); // 如果发的不是html内容去掉true参数
			message.addAttachment("testMyImg.gif", new ClassPathResource("doc/myImg.gif"));
//			message.addAttachment("Erlang-ch.pdf", new ClassPathResource("doc/Erlang-ch.pdf")); //添加附件
//			message.addInline("myLogo.gif",new ClassPathResource("doc/myImg.gif"));
//			System.out.println(System.getProperty("java.class.path"));
			javaMailSender.send(msg);
            
        } catch (MessagingException e) {
        	e.printStackTrace();
            if(log.isWarnEnabled()) {
                log.warn("邮件信息导常! 邮件标题为: "+title);
            }
            return false;
        } catch (MailException me) {
        	me.printStackTrace();
            if(log.isWarnEnabled()) {
                log.warn("发送邮件失败! 邮件标题为: "+title);
            }
            return false;
        }
        return true;    
    }
    
    
    /**
     * 邮件模板中得到信息
     * @return 返回特发送的内容
     */
    private String getMessage() {
        try {
			return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateLocation, encoding, model);
		} catch (VelocityException e) {
			e.printStackTrace();
			log.error("邮件模板读取失败!邮件标题为: "+title);
		}
		return "";
    }

    private String[] createToEmail(String to) {
        return new String[] {to};
    }
    
    public void setToEmail(String to) {
        setToEmails(createToEmail(to));
    }
    
    public void setJavaMailSender(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }
    
    public void setVelocityEngine(VelocityEngine velocityEngine) {
        this.velocityEngine = velocityEngine;
    }

    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    public void setModel(Map<String,String> model) {
        this.model = model;
    }

    public void setTemplateLocation(String templateLocation) {
        this.templateLocation = templateLocation;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setToEmails(String[] toEmails) {
        this.toEmails = toEmails;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getTemplateLocation() {
        return templateLocation;
    }
}

写一个Velocity模板hello.vm:放在velocity下

 

${username},您好,欢迎来到<a href="http://i.firefoxchina.cn/" target="_blank">欢迎来到firfox</a>!

 

接下来 测试一下吧

public class TestMailSend {
	
	public static void main(String[] args) {
		MailUtil mailUtil = (MailUtil) new ClassPathXmlApplicationContext("applicationContext.xml").getBean("mailUtil");
		Map<String, String> data = new HashMap<String, String>();
		data.put("username", "mir liu");
		mailUtil.setTemplateLocation("hello.vm");
		mailUtil.setModel(data);
		mailUtil.setToEmail("[email protected]");
		mailUtil.setTitle("mail with veloctiy and spring");
		System.out.println("发送中请等待.....");
		mailUtil.send();
		System.out.println("发送成功.....");
	}
}

 

 测试通过的话我们接下来就开始写quartz 触发器调用的类了:

 

package com.ryt.mail;

import java.util.HashMap;
import java.util.Map;

public class MailManager {
	MailUtil mailUtil;
	
	public void setMailUtil(MailUtil mailUtil) {
		this.mailUtil = mailUtil;
	}

	public void sendMail(){
		Map<String, String> data = new HashMap<String, String>();
		data.put("username", "mir liu");
		mailUtil.setTemplateLocation("hello.vm");
		mailUtil.setModel(data);
		mailUtil.setToEmail("[email protected]");
		mailUtil.setTitle("auto send mail with veloctiy and spring!!!");
		boolean isSuccess=mailUtil.send();
		if(isSuccess)
		   System.out.println("quartz 发送成功.....");
		else
		   System.out.println("发送失败!!!");
	}
}

 

 那么这个怎么测试呢?把这个部分改成你电脑 马上要到的时间

  <property name="cronExpression" value="0 0 12 * * ?" />

 

这个是Quartz的cron表达式 ,该怎么改还是baidu一下吧

 

所有环节都完成。

你可能感兴趣的:(spring,quartz,mail,定时发送)