使用spring 并加载模板发送Email 发邮件 java 模板

以下例子是使用spring发送email,然后加载到固定的模板,挺好的,大家可以试试

需要使用到spring-context 包 和 com.springsource.org.apache.velocity-1.6.2.jar 其他都是常用包,自选,包括commons 系列包

代码如下

package asia.wildfire.mail;


import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

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

/**
 * Created with IntelliJ IDEA.
 * User: liuxiaochen
 * Date: 13-9-22
 * Time: 下午6:50
 * 修改描述
 */
public class ActsocialMailSender {
    //从配置文件中读取相应的邮件配置属性
    private static final String emailHost = "smtp.gmail.com";
    private static final String userName = "****@gmail.com";
    private static final String password = "********";
    private static final String mailAuth = "true";
    private static Map<String, Object> proMap = null;
    private static JavaMailSenderImpl instance = null;
    private static VelocityEngine velocityEngine = null;

    static {
        proMap = new HashMap<String, Object>();
        proMap.put("resource.loader", "class");
        proMap.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");

    }

    public static JavaMailSender getInstance() {
        if (null == instance) {
            synchronized (JavaMailSenderImpl.class) {
                if (null == instance) {
                    instance = new JavaMailSenderImpl();
                    instance.setHost(emailHost);
                    instance.setUsername(userName);
                    instance.setPassword(password);
                    Properties properties = new Properties();
                    properties.setProperty("mail.smtp.auth", mailAuth);
                    //使用gmail发送邮件是必须设置如下参数的 主要是port不一样
                    if (emailHost.indexOf("smtp.gmail.com")>=0) {
                        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                        properties.setProperty("mail.smtp.socketFactory.fallback", "false");
                        properties.setProperty("mail.smtp.port", "465");
                        properties.setProperty("mail.smtp.socketFactory.port", "465");
                    }
                    instance.setJavaMailProperties(properties);
                }
            }
        }

        return instance;
    }

    public static VelocityEngine getVelocityEngineInstance() {
        if (null == velocityEngine) {
            synchronized (VelocityEngine.class) {
                if (null == velocityEngine) {
                    velocityEngine = new VelocityEngine();
                    for (Map.Entry<String, Object> entry : proMap.entrySet()) {
                        velocityEngine.setProperty(entry.getKey(), entry.getValue());
                    }
                }
            }
        }
        return velocityEngine;
    }

    public static 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,"GBK");
                //这是一个生成Mime邮件简单工具,如果不使用GBK这个,中文会出现乱码
                //如果您使用的都是英文,那么可以使用MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                message.setTo(mailTo);//设置接收方的email地址
                message.setSubject(subject);//设置邮件主题
                message.setFrom(userName);//设置发送方地址
                String text = VelocityEngineUtils.mergeTemplateIntoString(
                        ActsocialMailSender.getVelocityEngineInstance(), vmfile, "UTF-8", model);
                //从模板中加载要发送的内容,vmfile就是模板文件的名字
                //注意模板中有中文要加GBK,model中存放的是要替换模板中字段的值
                message.setText(text, true);
                //将发送的内容赋值给MimeMessageHelper,后面的true表示内容解析成html
                //如果您不想解析文本内容,可以使用false或者不添加这项
                FileSystemResource file;
                for(String s:files)//添加附件
                {
                    file = new FileSystemResource(new File(s));//读取附件
                    message.addAttachment(s, file);//向email中添加附件
                }
            }
        };
        ActsocialMailSender.getInstance().send(preparator);//发送邮件
    }
    
    public static void sendAlertEmail(final Map<String,Object> model,final String[] mailTo){
    	sendEmail(model, "", "", mailTo, new String[]{});
    }
}

以上代码就是发送邮件所需要的代码,可以看下

测试类

public class ActsocialEmailTest {
    public static void main(String[] args) {
        Map<String,Object> model = new HashMap<String,Object>();
        model.put("userName","xiaochen.liu");
        model.put("emailAddress", "xiaochen.liu@xingxinghuo.com");
        ActsocialMailSender.sendEmail(model,"欢迎加入", "welcome.vm",new String[]{"****@gmail.com"},new String[]{});

    }
}

模板文件如下

welcome.vm

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

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

</html>

好了就这么多


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值