EDM推送

EDM推送

一、需求描述:
    
    日前,做了一个发送客户账单的功能,邮件模板采用自定义,生成vm文件,保存至redis,
    采用jodd-mail发送邮件,查询用户账单数据,账单明细,缓存加载模板并渲染数据,推送邮件至客户端.
    这里给大家推荐一下,jodd是一款很优秀的分类工具插件,邮件服务可以说是使用超级简单,
    但是性能很不错,实现代码干净利落;
    
二、Velocity的基本代码实现
  

 1 VelocityEngine ve = new VelocityEngine();
 2 ve.setProperty(Velocity.INPUT_ENCODING, "utf-8");// 设置输入字符集
 3 ve.setProperty(Velocity.OUTPUT_ENCODING, "utf-8");// 设置输出字符集
 4 ve.init();
 5     
 6 VelocityContext context = new VelocityContext();
 7 HashMap<String, Object> result = new HashMap<String, Object>();
 8 result.put("name", "麦德漂");
 9 result.put("age", "26")
10 context.put("map", result);
11     
12 //ve.evaluate(context, writer, "logTag", StringTemplate);
13 ve.evaluate(context, writer, "logTag", "第一列:$map.get('name'),第二列:$map.get('key')");
14 String content = writer.toString();
15 writer.close();

 比较简单,如果缓存中没有模板内容,重新加载一遍

1 VelocityContext context = new VelocityContext();
2 StringWriter writer = new StringWriter();
3 Template t = ve.getTemplate("/First.vm");
4 t.merge(context, writer);
5 String content = writer.toString();
6 writer.close();

  或者从本地文件去加载

1 VelocityEngine ve = new VelocityEngine();
2 ve.setProperty(Velocity.RESOURCE_LOADER, "file");
3 ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, "/test/test/template/");
4 ve.setProperty(Velocity.INPUT_ENCODING, "utf-8");
5 ve.setProperty(Velocity.OUTPUT_ENCODING, "utf-8");
6 ve.init();

三、采用jodd发送邮件
    

   1.Jodd的流式编程:

1 Email email = Email.create().from("...@jodd.org").to("...@jodd.org").subject("Hello!").addText("text").addHtml("<b>HTML</b> message...");

   2.Jodd的邮件推送

1 SmtpServer smtpServer = SmtpServer.create("mail.jodd.org").authenticateWith("user", "password");
2 SendMailSession session = smtpServer.createSession(); 3 session.open(); 4 session.sendMail(email1); 5 session.sendMail(email2); 6 session.close();

   3.考虑到发送效率,避免进入垃圾箱,我目前每500封邮件关闭一次session,session中的邮件全部发送,保存发送记录,
      停顿10秒,失败时记录用户数据,支持失败重发.
      
四、关于统计邮件已读,未读


    邮件发送出去,很多时候我们很在意用户是否已读,刚开始有两种思路:
    1.邮件设置已读回执,这种解决方案需要用户来触发,交互性不好,且统计不一定准确,直接放弃
    2.在邮箱内容中添加隐藏图片,很简单,如下:

1 <img style='display:none;' src='" + countUrl + id + "'/>

    这样用户在打开邮件时,会加载图片重新打到你的服务器,方便监控已读未读情况.
    
    注:在使用OutLook时,隐藏图片无法隐藏,最后我的统计路径输出了一张无色的java矢量图,当然很小,同样扔到redis了.