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.   
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  9. <html>  
  10.   <head>  
  11.     <base href="<%=basePath%>">  
  12.       
  13.     <title>忘记密码</title>  
  14.       
  15.     <meta http-equiv="pragma" content="no-cache">  
  16.     <meta http-equiv="cache-control" content="no-cache">  
  17.     <meta http-equiv="expires" content="0">      
  18.   
  19.   </head>  
  20.     
  21.   <body>  
  22.     <h2>忘记密码处理</h2>  
  23.     <form action="forgetPassword" name="form1" method="post">  
  24.         您的注册邮箱:<input type="text" name="user.userId" value=""/>  
  25.         <input type="submit" value=" 提交  ">  
  26.     </form>  
  27.   </body>  
  28. </html>  



MailAction.java:

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


applicationContext.xml部分:

  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
  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:

  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.                                           
  41.                                 </tr>  
  42.                             </table></td>  
  43.                     </tr>  
  44.                 </table></td>  
  45.         </tr>  
  46.     </table>  
  47.     <img src='cid:file'/>  
  48. </body>  
  49. </html> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值