Java spring多账号发送邮件

作者:じ☆ve宝贝

发布时间:2015-09-15T14:59:38

需要的jar包velocity-1.5.jar mail.jar

配置文件config.properties

mail.host=smtp.ym.163.com
mail.username=service@studyjava.cn
mail.smtp.auth=true
mail.smtp.timeout=25000

配置文件Const.java

//mail
	public static final String MAILUSERLIST="system1@studyjava.cn,system2@studyjava.cn,system3@studyjava.cn,system4@studyjava.cn,system5@studyjava.cn,system6@studyjava.cn,system7@studyjava.cn,system8@studyjava.cn,system9@studyjava.cn,system10@studyjava.cn";
	public static final String MAILPASSWORD="www.studyjava.cn";

register.vm模板


亲爱的 <b style="color:red;">${username}</b>: 您好!<br/><br/>
    你的登录邮箱为:${useremail}<br/>
    请点击下面链接,完成您的邮箱验证:<br/>
    <a href='${sureurl}' >${sureurl}</a><br/>

    如果以上链接无法点击请点击这里<a href='${sureurl}' style="color:red;">立即激活</a>,或将上面的地址复制到你的浏览器(如IE)的地址栏。<br/>
  (该链接在48小时内有效,48小时后需要重新注册) <br/><br/><br/>
<br/><br/><br/>
<center style="color:red;font-size:10px">
温馨提示:此邮件由CIA验证平台系统发送,请勿直接回复。
</center>

####applictionContext-mail.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"  
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">  
 
    <!-- 邮件发送器 -->  
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">  
		<property name="host" value="${mail.host}" />  
		<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>  
  
  
    <bean id="velocityEngine"  
        class="org.springframework.ui.velocity.VelocityEngineFactoryBean">  
        <property name="resourceLoaderPath" value="classpath:cn/studyjava/util"></property>  
    </bean>  
 
    <bean id="mailService" class="cn.studyjava.service.MailService">  
        <property name="javaMailSender" ref="mailSender"></property>  
        <property name="encoding" value="UTF-8"></property>  
        <property name="templateLocation" value="register.vm"></property>  
        <property name="velocityEngine" ref="velocityEngine"></property>  
        <property name="title" value="测试邮件"></property>  
    </bean>  
  
</beans>  

####s pring.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:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop" 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.2.xsd 
							http://www.springframework.org/schema/tx 
							http://www.springframework.org/schema/tx/spring-tx-3.2.xsd 
							http://www.springframework.org/schema/aop 
							http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
							http://www.springframework.org/schema/context 
							http://www.springframework.org/schema/context/spring-context-3.2.xsd"
	default-lazy-init="true">

	<context:property-placeholder
		location="classpath:/cn/studyjava/config.properties" />
	<!-- 导入mail配置文件-->
	<import resource="classpath:/cn/studyjava/applictionContext-mail.xml" />
</beans>

MailService.java

package cn.studyjava.service;

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.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.velocity.VelocityEngineUtils;

import cn.studyjava.util.Const;

/**
 * 
 * 邮件发送器 zsl
 * 
 * Velocity类中使用init方法里是使用了RuntimeSingleton.init();
 * 在RuntimeSingleton类中,使用到的运行实例是静态new出来的。 private static RuntimeInstance ri =
 * new RuntimeInstance();
 * 而在org.apache.velocity.app.VelocityEngine类中,并没有一个单例类来初始化, 每次都会使用private
 * RuntimeInstance ri = new RuntimeInstance()来创建一个新的运行实例,
 * 这样就使得每个velocity引擎都会拥有各自的实例,互不干扰。搜索
 */

public class MailService {

	protected final Log log = LogFactory.getLog(getClass());

	private JavaMailSenderImpl javaMailSender;
	// 一个初始化单例的velocity实例的类。
	private VelocityEngine velocityEngine;
	private String title;
	private String encoding;
	private String templateLocation;
	private String[] toEmails;
	private Map<String, Object> model;

	public boolean send() {
		try {
			MimeMessage msg = javaMailSender.createMimeMessage();
			MimeMessageHelper message = new MimeMessageHelper(msg, true,
					"UTF-8");
			//重点在这里,多账号是在这里认证的
			String username = Const.MAILUSERLIST.split(",")[(int)(Math.random()*10)];
			javaMailSender.setUsername(username);
			javaMailSender.setPassword(Const.MAILPASSWORD);
			message.setFrom(username);
			message.setSubject(title);
			message.setTo(toEmails);
			message.setText(getMessage(), true); // 如果发的不是html内容去掉true参数
			// message.addInline("myLogo",new
			// ClassPathResource("img/mylogo.gif"));
			// message.addAttachment("myDocument.pdf", new
			// ClassPathResource("doc/myDocument.pdf"));
			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(JavaMailSenderImpl 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, Object> 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 String getTemplateLocation() {
		return templateLocation;
	}
	
}

测试法方法

注入service后直接调用下面内容即可发送邮件

			Map<String, Object> data = new HashMap<String, Object>();
			data.put("username", ciaDeveloper.getName());
			data.put("useremail", ciaDeveloper.getEmail());
			data.put("sureurl", "http://www.studyjava.cn");
			// java模板引擎(velocity)apache的开源项目velocity做的文件就是.vm后缀
			mailService.setTemplateLocation("register.vm");
			mailService.setModel(data);
			mailService.setToEmail(ciaDeveloper.getEmail());
			mailService.setTitle("激活CIA验证服务帐号");
			mailService.send();
			System.out.println("邮件发送成功!!");