spring使用模板发送邮件及附件笔记

需要引用的jar包:

mail-1.4.1.jar

activation-1.1.jar

spring-context-support-2.5.jar

spring-webmvc.jar

 

  1. 前台页面

    forgetPassword.jsp:

  2. <%@ page language=”java” import=”java.util.*” pageEncoding=”UTF-8″%>
  3. <%
  4. String path = request.getContextPath();
  5. String basePath = request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+path+”/”;
  6. %>
  7. <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
  8. <html>
  9.   <head>
  10.     <base href=”<%=basePath%>”>
  11.     <title>忘记密码</title>
  12.     <meta http-equiv=”pragma” content=”no-cache”>
  13.     <meta http-equiv=”cache-control” content=”no-cache”>
  14.     <meta http-equiv=”expires” content=”0″>
  15.   </head>
  16.   <body>
  17.     <h2>忘记密码处理</h2>
  18.     <form action=”forgetPassword” name=”form1″ method=”post”>
  19.         您的注册邮箱:<input type=”text” name=”user.userId” value=””/>
  20.         <input type=”submit” value=” 提交  “>
  21.     </form>
  22.   </body>
  23. </html>

 

MailAction.java:

[java][/java] view plaincopy

  1. package com.gifer.action;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.UnsupportedEncodingException;
  5. import java.text.SimpleDateFormat;
  6. import java.util.Date;
  7. import java.util.HashMap;
  8. import java.util.Map;
  9. import javax.mail.MessagingException;
  10. import javax.mail.internet.MimeMessage;
  11. import javax.mail.internet.MimeUtility;
  12. import org.slf4j.Logger;
  13. import org.slf4j.LoggerFactory;
  14. import org.springframework.core.io.FileSystemResource;
  15. import org.springframework.mail.SimpleMailMessage;
  16. import org.springframework.mail.javamail.JavaMailSenderImpl;
  17. import org.springframework.mail.javamail.MimeMessageHelper;
  18. import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
  19. import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
  20. import com.gifer.model.LoginUser;
  21. import com.opensymphony.xwork2.ActionSupport;
  22. import freemarker.template.Template;
  23. import freemarker.template.TemplateException;
  24. public class MailAction extends ActionSupport {
  25.     /**
  26.      *
  27.      */
  28.     private static final long serialVersionUID = 4962937405531604950L;
  29.     private static final Logger log = LoggerFactory.getLogger(MailAction.class);
  30.     private JavaMailSenderImpl mailSender;
  31.     private SimpleMailMessage mailMessage;
  32.     private FreeMarkerConfigurer freeMarkerConfigurer;
  33.     private LoginUser user;
  34.     public void setMailSender(JavaMailSenderImpl mailSender) {
  35.         this.mailSender = mailSender;
  36.     }
  37.     public void setMailMessage(SimpleMailMessage mailMessage) {
  38.         this.mailMessage = mailMessage;
  39.     }
  40.     public void setUser(LoginUser user) {
  41.         this.user = user;
  42.     }
  43.     public void setFreeMarkerConfigurer(
  44.             FreeMarkerConfigurer freeMarkerConfigurer) {
  45.         this.freeMarkerConfigurer = freeMarkerConfigurer;
  46.     }
  47.     @Override
  48.     public String execute() throws Exception {
  49.         // String content = “hello,” + user.getUserId()
  50.         // + “,您的临时密码是:123456,请及时登录修改。”;
  51.         // 发送简单邮件
  52.         // this.sendSimpleMail(content);
  53.         // 发送html邮件
  54.         // this.sendHtmlMail(content);
  55.         this.sendTemplateMail();
  56.         return SUCCESS;
  57.     }
  58.     // 发送简单文本内容邮件
  59.     private void sendSimpleMail(String content) {
  60.         this.mailMessage.setTo(user.getUserId());// 邮件接收者
  61.         this.mailMessage.setText(content);// 邮件内容
  62.         this.mailSender.send(mailMessage);// 发送
  63.     }
  64.     // 发送HTML内容邮件
  65.     private void sendHtmlMail(String content) {
  66.         MimeMessage mailMsg = this.mailSender.createMimeMessage();
  67.         MimeMessageHelper messageHelper = new MimeMessageHelper(mailMsg);
  68.         String html = “<html><head></head><body><h1>Hello</h1>” + content
  69.                 + “</body></html>”;
  70.         try {
  71.             messageHelper.setTo(user.getUserId());
  72.             messageHelper.setText(html, true);// true 表示启动HTML格式的邮件
  73.         } catch (MessagingException e) {
  74.             log.error(e.getMessage(), e);
  75.         }
  76.         this.mailSender.send(mailMessage);// 发送
  77.     }
  78.     // 发送邮件内容采用模板
  79.     public void sendTemplateMail() {
  80.         try {
  81.             MimeMessage mailMsg = this.mailSender.createMimeMessage();
  82.             MimeMessageHelper messageHelper = new MimeMessageHelper(mailMsg,
  83.                     true, “UTF-8”);
  84.             messageHelper.setTo(user.getUserId());// 接收邮箱
  85.             messageHelper.setFrom(this.mailMessage.getFrom());// 发送邮箱
  86.             messageHelper.setSentDate(new Date());// 发送时间
  87.             messageHelper.setSubject(this.mailMessage.getSubject());// 邮件标题
  88.             // true 表示启动HTML格式的邮件
  89.             messageHelper.setText(this.getMailText(), true);// 邮件内容
  90.             // 添加邮件附件
  91.             FileSystemResource rarfile = new FileSystemResource(new File(
  92.                     “E:\\UploadFileDemo\\mail图片测试.png”));
  93.             // addAttachment addInline 两种附件添加方式
  94.             // 以附件的形式添加到邮件
  95.             // 使用MimeUtility.encodeWord 解决附件名中文乱码的问题
  96.             messageHelper.addAttachment(MimeUtility.encodeWord(“mail图片测试.png”),
  97.                     rarfile);
  98.             // <img src=’cid:file’/> 此处将文件内容嵌入邮件页面中
  99.             // 这里的’cid:file’与addInline(‘file’,rarfile)中的file对应
  100.             messageHelper.addInline(“file”, rarfile);
  101.             this.mailSender.send(mailMsg);// 发送
  102.         } catch (MessagingException e) {
  103.             log.error(e.getMessage(), e);
  104.         } catch (UnsupportedEncodingException e) {
  105.             log.error(e.getMessage(), e);
  106.         }
  107.     }
  108.     /**
  109.      * 获取模板并将内容输出到模板
  110.      *
  111.      * @param content
  112.      * @return
  113.      */
  114.     private String getMailText() {
  115.         String html = “”;
  116.         try {
  117.             Map map = new HashMap();
  118.             map.put(“userName”, “greensurfer”);
  119.             map.put(“userId”, user.getUserId());
  120.             map.put(“password”, “123456”);
  121.             SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-mm-dd hh:mm:ss”);
  122.             map.put(“sendTime”, sdf.format(new Date()));
  123.             // 装载模板
  124.             Template tpl = this.freeMarkerConfigurer.getConfiguration()
  125.                     .getTemplate(“forgetPassword.ftl”);
  126.             // 加入map到模板中 输出对应变量
  127.             html = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);
  128.         } catch (IOException e) {
  129.             e.printStackTrace();
  130.         } catch (TemplateException e) {
  131.             e.printStackTrace();
  132.         }
  133.         return html;
  134.     }
  135. }

applicationContext.xml部分:

[html][/html] view plaincopy

  1. <!– 邮件发送方配置bean –>
  2.     <bean id=”mailSender” class=”org.springframework.mail.javamail.JavaMailSenderImpl”>
  3.         <property name=”host” value=”smtp.163.com” />
  4.         <!– mail account –>
  5.         <property name=”username” value=”gifer” />
  6.         <property name=”password” value=”123456″ />
  7.         <property name=”javaMailProperties”>
  8.             <props>
  9.                 <prop key=”mail.smtp.auth”>true</prop>
  10.             </props>
  11.         </property>
  12.     </bean>
  13.     <!– 邮件发送模板 –>
  14.     <bean id=”mailMessage” class=”org.springframework.mail.SimpleMailMessage”>
  15.         <property name=”from” value=”xxxxxxx@163.com” />
  16.         <property name=”subject” value=”帐户密码忘记邮件” />
  17.     </bean>
  18.     <!– 配置发送模板bean–>
  19.     <bean id=”freeMarkerConfigurer”
  20.         class=”org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer”>
  21.         <property name=”templateLoaderPaths” value=”classpath:mailTemplate” /><!– 模板路径位置 –>
  22.         <property name=”freemarkerSettings”>
  23.             <props>
  24.                 <prop key=”template_update_delay”>1800</prop><!– 模板更新延时 –>
  25.                 <prop key=”default_encoding”>UTF-8</prop>
  26.                 <prop key=”locale”>zh_CN</prop>
  27.             </props>
  28.         </property>
  29.     </bean>
  30.     <bean id=”mailAction” class=”com.gifer.action.MailAction”
  31.         abstract=”false” scope=”prototype” lazy-init=”default” autowire=”default”
  32.         dependency-check=”default”>
  33.         <property name=”mailSender”>
  34.             <ref bean=”mailSender” />
  35.         </property>
  36.         <property name=”mailMessage”>
  37.             <ref bean=”mailMessage” />
  38.         </property>
  39.         <property name=”freeMarkerConfigurer”>
  40.             <ref bean=”freeMarkerConfigurer”/>
  41.         </property>
  42.     </bean>

 

 

struts.xml

[html][/html] view plaincopy

  1. <action name=”forgetPassword” class=”mailAction”>
  2.             <result name=”success”>jsp/mailSuccess.jsp</result>
  3.             <result name=”input”>jsp/forgetPassword.jsp</result>
  4.         </action>

 

 

 

模板文件

forgetPassword.ftl:

[html][/html] view plaincopy

  1. <!DOCTYPE head PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
  2. <html>
  3. <head>
  4. <title></title>
  5. <meta HTTP-EQUIV=”Content-Type” CONTENT=”text/html; charset=utf-8″>
  6. <style type=”text/css”>
  7. body {
  8.     font-size: 14px;
  9.     line-height: 1.5
  10. }
  11. </style>
  12. </head>
  13. <body>
  14.     <table cellspacing=”0″ cellpadding=”20″>
  15.         <tr>
  16.             <td>
  17.                 <table width=”500″ cellspacing=”0″ cellpadding=”1″>
  18.                     <tr>
  19.                         <td bgcolor=”#FF8E00″ align=”left”
  20.                             style=”font-family:’lucida grande’,tahoma,’bitstream vera sans’,helvetica,sans-serif;line-height:150%;color:#FFF;font-size:24px;font-weight:bold;padding:4px”>
  21.                             GIFER社区
  22.                         <th></th>
  23.                     </tr>
  24.                     <tr>
  25.                         <td bgcolor=”#FF8E00″>
  26.                             <table width=”100%” cellspacing=”0″ bgcolor=”#FFFFFF”
  27.                                 cellpadding=”20″>
  28.                                 <tr>
  29.                                     <td
  30.                                         style=”font-family:’lucida grande’,tahoma,’bitstream vera sans’,helvetica,sans-serif;line-height:150%;color:#000;font-size:14px;”>
  31.                                         亲爱的${userName}:
  32.                                         <blockquote>
  33.                                             <br> <strong>您在gifer.com的帐户${userId}密码忘记了?该邮件为你提供临时密码:${password},请及时登录,修改您的密码。</strong><br>
  34.                                             <br>如果下面链接不可用,请复制下面的链接到浏览器进行访问,以便修改你的帐户密码。<br>帐户密码修改链接:<br>
  35.                                             <a href=”http://localhost:10002/UserManager/” target=”_blank”>http://localhost:10002/UserManager/</a><br>
  36.                                             <br>
  37.                                         </blockquote> <br> <br>GIFER 社区<br> <a
  38.                                         href=”http://localhost:10002/UserManager/” target=”_blank”>http://localhost:10002/UserManager/</a>
  39.                                         <br>发送时间:${sendTime}<br> <br>此邮件为系统自动发出,请勿回复。</td>
  40.                                 </tr>
  41.                             </table></td>
  42.                     </tr>
  43.                 </table></td>
  44.         </tr>
  45.     </table>
  46.     <img src=’cid:file’/>
  47. </body>
  48. </html>

标签