需要引用的jar包:
mail-1.4.1.jar
activation-1.1.jar
spring-context-support-2.5.jar
spring-webmvc.jar
前台页面
forgetPassword.jsp:
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>忘记密码</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- </head>
- <body>
- <h2>忘记密码处理</h2>
- <form action="forgetPassword" name="form1" method="post">
- 您的注册邮箱:<input type="text" name="user.userId" value=""/>
- <input type="submit" value=" 提交 ">
- </form>
- </body>
- </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>忘记密码</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<h2>忘记密码处理</h2>
<form action="forgetPassword" name="form1" method="post">
您的注册邮箱:<input type="text" name="user.userId" value=""/>
<input type="submit" value=" 提交 ">
</form>
</body>
</html>
MailAction.java:
- package com.gifer.action;
- import java.io.File;
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Map;
- import javax.mail.MessagingException;
- import javax.mail.internet.MimeMessage;
- import javax.mail.internet.MimeUtility;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.core.io.FileSystemResource;
- import org.springframework.mail.SimpleMailMessage;
- import org.springframework.mail.javamail.JavaMailSenderImpl;
- import org.springframework.mail.javamail.MimeMessageHelper;
- import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
- import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
- import com.gifer.model.LoginUser;
- import com.opensymphony.xwork2.ActionSupport;
- import freemarker.template.Template;
- import freemarker.template.TemplateException;
- public class MailAction extends ActionSupport {
- /**
- *
- */
- private static final long serialVersionUID = 4962937405531604950L;
- private static final Logger log = LoggerFactory.getLogger(MailAction.class);
- private JavaMailSenderImpl mailSender;
- private SimpleMailMessage mailMessage;
- private FreeMarkerConfigurer freeMarkerConfigurer;
- private LoginUser user;
- public void setMailSender(JavaMailSenderImpl mailSender) {
- this.mailSender = mailSender;
- }
- public void setMailMessage(SimpleMailMessage mailMessage) {
- this.mailMessage = mailMessage;
- }
- public void setUser(LoginUser user) {
- this.user = user;
- }
- public void setFreeMarkerConfigurer(
- FreeMarkerConfigurer freeMarkerConfigurer) {
- this.freeMarkerConfigurer = freeMarkerConfigurer;
- }
- @Override
- public String execute() throws Exception {
- // String content = "hello," + user.getUserId()
- // + ",您的临时密码是:123456,请及时登录修改。";
- // 发送简单邮件
- // this.sendSimpleMail(content);
- // 发送html邮件
- // this.sendHtmlMail(content);
- this.sendTemplateMail();
- return SUCCESS;
- }
- // 发送简单文本内容邮件
- private void sendSimpleMail(String content) {
- this.mailMessage.setTo(user.getUserId());// 邮件接收者
- this.mailMessage.setText(content);// 邮件内容
- this.mailSender.send(mailMessage);// 发送
- }
- // 发送HTML内容邮件
- private void sendHtmlMail(String content) {
- MimeMessage mailMsg = this.mailSender.createMimeMessage();
- MimeMessageHelper messageHelper = new MimeMessageHelper(mailMsg);
- String html = "<html><head></head><body><h1>Hello</h1>" + content
- + "</body></html>";
- try {
- messageHelper.setTo(user.getUserId());
- messageHelper.setText(html, true);// true 表示启动HTML格式的邮件
- } catch (MessagingException e) {
- log.error(e.getMessage(), e);
- }
- this.mailSender.send(mailMessage);// 发送
- }
- // 发送邮件内容采用模板
- public void sendTemplateMail() {
- try {
- MimeMessage mailMsg = this.mailSender.createMimeMessage();
- MimeMessageHelper messageHelper = new MimeMessageHelper(mailMsg,
- true, "UTF-8");
- messageHelper.setTo(user.getUserId());// 接收邮箱
- messageHelper.setFrom(this.mailMessage.getFrom());// 发送邮箱
- messageHelper.setSentDate(new Date());// 发送时间
- messageHelper.setSubject(this.mailMessage.getSubject());// 邮件标题
- // true 表示启动HTML格式的邮件
- messageHelper.setText(this.getMailText(), true);// 邮件内容
- // 添加邮件附件
- FileSystemResource rarfile = new FileSystemResource(new File(
- "E:\\UploadFileDemo\\mail图片测试.png"));
- // addAttachment addInline 两种附件添加方式
- // 以附件的形式添加到邮件
- // 使用MimeUtility.encodeWord 解决附件名中文乱码的问题
- messageHelper.addAttachment(MimeUtility.encodeWord("mail图片测试.png"),
- rarfile);
- // <img src='cid:file'/> 此处将文件内容嵌入邮件页面中
- // 这里的'cid:file'与addInline('file',rarfile)中的file对应
- messageHelper.addInline("file", rarfile);
- this.mailSender.send(mailMsg);// 发送
- } catch (MessagingException e) {
- log.error(e.getMessage(), e);
- } catch (UnsupportedEncodingException e) {
- log.error(e.getMessage(), e);
- }
- }
- /**
- * 获取模板并将内容输出到模板
- *
- * @param content
- * @return
- */
- private String getMailText() {
- String html = "";
- try {
- Map map = new HashMap();
- map.put("userName", "greensurfer");
- map.put("userId", user.getUserId());
- map.put("password", "123456");
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
- map.put("sendTime", sdf.format(new Date()));
- // 装载模板
- Template tpl = this.freeMarkerConfigurer.getConfiguration()
- .getTemplate("forgetPassword.ftl");
- // 加入map到模板中 输出对应变量
- html = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);
- } catch (IOException e) {
- e.printStackTrace();
- } catch (TemplateException e) {
- e.printStackTrace();
- }
- return html;
- }
- }
package com.gifer.action;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import com.gifer.model.LoginUser;
import com.opensymphony.xwork2.ActionSupport;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class MailAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 4962937405531604950L;
private static final Logger log = LoggerFactory.getLogger(MailAction.class);
private JavaMailSenderImpl mailSender;
private SimpleMailMessage mailMessage;
private FreeMarkerConfigurer freeMarkerConfigurer;
private LoginUser user;
public void setMailSender(JavaMailSenderImpl mailSender) {
this.mailSender = mailSender;
}
public void setMailMessage(SimpleMailMessage mailMessage) {
this.mailMessage = mailMessage;
}
public void setUser(LoginUser user) {
this.user = user;
}
public void setFreeMarkerConfigurer(
FreeMarkerConfigurer freeMarkerConfigurer) {
this.freeMarkerConfigurer = freeMarkerConfigurer;
}
@Override
public String execute() throws Exception {
// String content = "hello," + user.getUserId()
// + ",您的临时密码是:123456,请及时登录修改。";
// 发送简单邮件
// this.sendSimpleMail(content);
// 发送html邮件
// this.sendHtmlMail(content);
this.sendTemplateMail();
return SUCCESS;
}
// 发送简单文本内容邮件
private void sendSimpleMail(String content) {
this.mailMessage.setTo(user.getUserId());// 邮件接收者
this.mailMessage.setText(content);// 邮件内容
this.mailSender.send(mailMessage);// 发送
}
// 发送HTML内容邮件
private void sendHtmlMail(String content) {
MimeMessage mailMsg = this.mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMsg);
String html = "<html><head></head><body><h1>Hello</h1>" + content
+ "</body></html>";
try {
messageHelper.setTo(user.getUserId());
messageHelper.setText(html, true);// true 表示启动HTML格式的邮件
} catch (MessagingException e) {
log.error(e.getMessage(), e);
}
this.mailSender.send(mailMessage);// 发送
}
// 发送邮件内容采用模板
public void sendTemplateMail() {
try {
MimeMessage mailMsg = this.mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMsg,
true, "UTF-8");
messageHelper.setTo(user.getUserId());// 接收邮箱
messageHelper.setFrom(this.mailMessage.getFrom());// 发送邮箱
messageHelper.setSentDate(new Date());// 发送时间
messageHelper.setSubject(this.mailMessage.getSubject());// 邮件标题
// true 表示启动HTML格式的邮件
messageHelper.setText(this.getMailText(), true);// 邮件内容
// 添加邮件附件
FileSystemResource rarfile = new FileSystemResource(new File(
"E:\\UploadFileDemo\\mail图片测试.png"));
// addAttachment addInline 两种附件添加方式
// 以附件的形式添加到邮件
// 使用MimeUtility.encodeWord 解决附件名中文乱码的问题
messageHelper.addAttachment(MimeUtility.encodeWord("mail图片测试.png"),
rarfile);
// <img src='cid:file'/> 此处将文件内容嵌入邮件页面中
// 这里的'cid:file'与addInline('file',rarfile)中的file对应
messageHelper.addInline("file", rarfile);
this.mailSender.send(mailMsg);// 发送
} catch (MessagingException e) {
log.error(e.getMessage(), e);
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
}
}
/**
* 获取模板并将内容输出到模板
*
* @param content
* @return
*/
private String getMailText() {
String html = "";
try {
Map map = new HashMap();
map.put("userName", "greensurfer");
map.put("userId", user.getUserId());
map.put("password", "123456");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
map.put("sendTime", sdf.format(new Date()));
// 装载模板
Template tpl = this.freeMarkerConfigurer.getConfiguration()
.getTemplate("forgetPassword.ftl");
// 加入map到模板中 输出对应变量
html = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
return html;
}
}
applicationContext.xml部分:
- <!-- 邮件发送方配置bean -->
- <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
- <property name="host" value="smtp.163.com" />
- <!-- mail account -->
- <property name="username" value="gifer" />
- <property name="password" value="123456" />
- <property name="javaMailProperties">
- <props>
- <prop key="mail.smtp.auth">true</prop>
- </props>
- </property>
- </bean>
- <!-- 邮件发送模板 -->
- <bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
- <property name="from" value="xxxxxxx@163.com" />
- <property name="subject" value="帐户密码忘记邮件" />
- </bean>
- <!-- 配置发送模板bean-->
- <bean id="freeMarkerConfigurer"
- class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
- <property name="templateLoaderPaths" value="classpath:mailTemplate" /><!-- 模板路径位置 -->
- <property name="freemarkerSettings">
- <props>
- <prop key="template_update_delay">1800</prop><!-- 模板更新延时 -->
- <prop key="default_encoding">UTF-8</prop>
- <prop key="locale">zh_CN</prop>
- </props>
- </property>
- </bean>
- <bean id="mailAction" class="com.gifer.action.MailAction"
- abstract="false" scope="prototype" lazy-init="default" autowire="default"
- dependency-check="default">
- <property name="mailSender">
- <ref bean="mailSender" />
- </property>
- <property name="mailMessage">
- <ref bean="mailMessage" />
- </property>
- <property name="freeMarkerConfigurer">
- <ref bean="freeMarkerConfigurer"/>
- </property>
- </bean>
<!-- 邮件发送方配置bean -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.163.com" />
<!-- mail account -->
<property name="username" value="gifer" />
<property name="password" value="123456" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
<!-- 邮件发送模板 -->
<bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="xxxxxxx@163.com" />
<property name="subject" value="帐户密码忘记邮件" />
</bean>
<!-- 配置发送模板bean-->
<bean id="freeMarkerConfigurer"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPaths" value="classpath:mailTemplate" /><!-- 模板路径位置 -->
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">1800</prop><!-- 模板更新延时 -->
<prop key="default_encoding">UTF-8</prop>
<prop key="locale">zh_CN</prop>
</props>
</property>
</bean>
<bean id="mailAction" class="com.gifer.action.MailAction"
abstract="false" scope="prototype" lazy-init="default" autowire="default"
dependency-check="default">
<property name="mailSender">
<ref bean="mailSender" />
</property>
<property name="mailMessage">
<ref bean="mailMessage" />
</property>
<property name="freeMarkerConfigurer">
<ref bean="freeMarkerConfigurer"/>
</property>
</bean>
- <action name="forgetPassword" class="mailAction">
- <result name="success">jsp/mailSuccess.jsp</result>
- <result name="input">jsp/forgetPassword.jsp</result>
- </action>
<action name="forgetPassword" class="mailAction">
<result name="success">jsp/mailSuccess.jsp</result>
<result name="input">jsp/forgetPassword.jsp</result>
</action>
forgetPassword.ftl:
- <!DOCTYPE head PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <title></title>
- <meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
- <style type="text/css">
- body {
- font-size: 14px;
- line-height: 1.5
- }
- </style>
- </head>
- <body>
- <table cellspacing="0" cellpadding="20">
- <tr>
- <td>
- <table width="500" cellspacing="0" cellpadding="1">
- <tr>
- <td bgcolor="#FF8E00" align="left"
- 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">
- GIFER社区
- <th></th>
- </tr>
- <tr>
- <td bgcolor="#FF8E00">
- <table width="100%" cellspacing="0" bgcolor="#FFFFFF"
- cellpadding="20">
- <tr>
- <td
- style="font-family:'lucida grande',tahoma,'bitstream vera sans',helvetica,sans-serif;line-height:150%;color:#000;font-size:14px;">
- 亲爱的${userName}:
- <blockquote>
- <br> <strong>您在gifer.com的帐户${userId}密码忘记了?该邮件为你提供临时密码:${password},请及时登录,修改您的密码。</strong><br>
- <br>如果下面链接不可用,请复制下面的链接到浏览器进行访问,以便修改你的帐户密码。<br>帐户密码修改链接:<br>
- <a href="http://localhost:10002/UserManager/" target="_blank">http://localhost:10002/UserManager/</a><br>
- <br>
- </blockquote> <br> <br>GIFER 社区<br> <a
- href="http://localhost:10002/UserManager/" target="_blank">http://localhost:10002/UserManager/</a>
- <br>发送时间:${sendTime}<br> <br>此邮件为系统自动发出,请勿回复。</td>
- </tr>
- </table></td>
- </tr>
- </table></td>
- </tr>
- </table>
- <img src='cid:file'/>
- </body>
- </html>