2010年8月23日星期一

Spring发送邮件-java发送email

Spring发送邮件-java发送email: "

最近碰到好多新手问我发送email的问题,特此整理代码如下,以供参考,不妥之处还请指出。


以我的工程为例,需以下准备工作:


1.spring2.5.jar


2.activation.jar


3.velocity-1.6.jar


4.mail-1.4.2.jar



接下来就是写代码了。


1.封装邮件发送器


package com.haixu.platform.pub;

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.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(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;
}
}



2.spring配置文件,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="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<!-- <value>classpath:mail.properties</value> -->
<value>/WEB-INF/properties/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>

<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="classpath:velocity"></property>
</bean>

<bean id="templateMail" class="com.haixu.platform.pub.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="www.cpuele.com"></property>
</bean>

</beans>

说明:模板文件放到classpath的velocity目录下,可自行改。



3.发送者邮件信息,mail.properties(WEB-INF下):


mail.from=yourname@gmail.com
mail.host=smtp.gmail.com
mail.password=yourpassword
mail.smtp.auth=true
mail.smtp.timeout=25000
mail.username=yourname


4.模板文件,hello.vm(classpath的velocity目录下):


${username},您好,欢迎来到恒特电器


5.测试Demo


MailUtil mailUtil = (MailUtil) SpringToolListener.getApplicationContext().getBean("templateMail");
Map<String, String> data = new HashMap<String, String>();
data.put("username", "村长");
mailUtil.setTemplateLocation("hello.vm");
mailUtil.setModel(data);
mailUtil.setToEmail("hengte@cpuele.com");
mailUtil.setTitle("mail with veloctiy and spring");
mailUtil.send();


注意:SpringToolListener是我自己的工具类,可将上述代码替换为MailUtil mailUtil = (MailUtil) context.getBean('templateMail');



tomcat下测试成功。











作者: jerryqiu007


声明: 本文系JavaEye网站发布的原创文章,未经作者书面许可,严禁任何网站转载本文,否则必将追究法律责任!




已有 0 人发表回复,猛击->>这里<<-参与讨论





JavaEye推荐






"

没有评论:

发表评论