spring 邮件发送

xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:flex="http://www.springframework.org/schema/flex"
    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.0.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
       http://www.springframework.org/schema/flex
       http://www.springframework.org/schema/flex/spring-flex-1.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:property-placeholder location="classpath:/email.properties"/>

    <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
      <property name="velocityProperties">
          <props>
          <prop key="resource.loader">class</prop>       
          <prop key="class.resource.loader.class">org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader</prop>       
          </props>
      </property>
   </bean>
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">  
        <property name="host" value="${email.host}" />  
        <property name="port" value="${email.port}" />  
        <property name="username" value="${email.username}" />  
        <property name="password" value="${email.password}" />  
        <property name="defaultEncoding" value="${email.encode}" />  
        <property name="javaMailProperties">  
            <props>  
                <prop key="mail.smtp.auth">${email.auth}</prop>  
            </props>  
        </property>  
    </bean>  
	<bean id="thirdVelocityEmailService" class="com.mongo.mail.ThirdVelocityEmailService">
		<property name="mailSender" ref="mailSender"></property> 
		<property name="velocityEngine" ref="velocityEngine"></property> 
	</bean>

</beans>

email.properties配置

email.host=smtp.163.com
email.port=25
[email protected]
email.password=1qaz!QAZ
email.auth=true
email.encode=utf-8
service实现:

package com.mongo.mail;
import java.io.File;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

public class EmailService {

    private JavaMailSender  mailSender;
    private VelocityEngine velocityEngine;

    public void setMailSender(JavaMailSender  mailSender)
    {
       this.mailSender = mailSender;
    }

    public void setVelocityEngine(VelocityEngine velocityEngine)
    {
       this.velocityEngine = velocityEngine;
    }

    public void sendEmail(final Map<String,Object> model,
				    		final String subject,
				    		final String vmfile,
				    		final String[] mailTo,
				    		final String [] files){  
    	
    	 MimeMessagePreparator preparator = new MimeMessagePreparator() {
         //注意MimeMessagePreparator接口只有这一个回调函数
         public void prepare(MimeMessage mimeMessage) throws Exception{
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true,"UTF-8");
            message.setTo(mailTo);//设置接收方的email地址
            message.setSubject(subject);//设置邮件主题
            message.setFrom("[email protected]");//设置发送方地址
            //从模板中加载要发送的内容,vmfile就是模板文件的名字
            //注意模板中有中文要加GBK,model中存放的是要替换模板中字段的值
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, vmfile,"UTF-8", model);
            //将发送的内容赋值给MimeMessageHelper,后面的true表示内容解析成html
            //如果您不想解析文本内容,可以使用false或者不添加这项
            message.setText(text, true);
            FileSystemResource file;
            for(String s:files)//添加附件
            {
               file = new FileSystemResource(new File(s));//读取附件
               message.addAttachment(s, file);//向email中添加附件
            }
          }
      };
       mailSender.send(preparator);//发送邮件
    }

}

test实现:

package com.mongo.mail;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmailTest {

    @Test
    public void sendEmail()
    {
       ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext-mail.xml");
       EmailService tves = (EmailService) context.getBean("emailService");
       Map<String,Object> model = new HashMap<String,Object>();
       model.put("userName","test");
       model.put("emailAddress", "[email protected]");
       //参数说明:替换velocity模板的变量和值对,邮件主题,velocity模板文件的路径,接收方email地址,附件
       //简单说明,如果您要群发,可以在接收方email地址中多传入几个email地址,附件可以一次发送多个
        tves.sendEmail(model,
		    		   "欢迎您的加入",
		    		   "com/mongo/mail/welcome.vm",
		    		   new String[]{"[email protected]"},
		    		   new String[]{"d:/Spring Security3.PDF"});
    }
}

vm:

<html>
<body>
<h3>您好 $!{userName}, 欢迎您加入!</h3>

<div>
    您的email地址是[$!{emailAddress}](mailto:${emailAddress}).
  本条信息是系统自动发送,请勿回复!
</div>
</body>

</html>



你可能感兴趣的:(spring 邮件发送)