场景:用于用户注册、密码重置等。
1 . 邮件html模板 emailTemplet.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>title>
<meta charset="utf-8" />
head>
<body>
<div class="qmbox qm_con_body_content qqmail_webmail_only" id="mailContentContainer" style="">
<style type="text/css">
.qmbox body {
margin: 0;
padding: 0;
background: #fff;
font-family: "Verdana, Arial, Helvetica, sans-serif";
font-size: 14px;
line-height: 24px;
}
.qmbox div, .qmbox p, .qmbox span, .qmbox img {
margin: 0;
padding: 0;
}
.qmbox img {
border: none;
}
.qmbox .contaner {
margin: 0 auto;
}
.qmbox .title {
margin: 0 auto;
background: url() #CCC repeat-x;
height: 30px;
text-align: center;
font-weight: bold;
padding-top: 12px;
font-size: 16px;
}
.qmbox .content {
margin: 4px;
}
.qmbox .biaoti {
padding: 6px;
color: #000;
}
.qmbox .xtop, .qmbox .xbottom {
display: block;
font-size: 1px;
}
.qmbox .xb1, .qmbox .xb2, .qmbox .xb3, .qmbox .xb4 {
display: block;
overflow: hidden;
}
.qmbox .xb1, .qmbox .xb2, .qmbox .xb3 {
height: 1px;
}
.qmbox .xb2, .qmbox .xb3, .qmbox .xb4 {
border-left: 1px solid #BCBCBC;
border-right: 1px solid #BCBCBC;
}
.qmbox .xb1 {
margin: 0 5px;
background: #BCBCBC;
}
.qmbox .xb2 {
margin: 0 3px;
border-width: 0 2px;
}
.qmbox .xb3 {
margin: 0 2px;
}
.qmbox .xb4 {
height: 2px;
margin: 0 1px;
}
.qmbox .xboxcontent {
display: block;
border: 0 solid #BCBCBC;
border-width: 0 1px;
}
.qmbox .line {
margin-top: 6px;
border-top: 1px dashed #B9B9B9;
padding: 4px;
}
.qmbox .neirong {
padding: 6px;
color: #666666;
}
.qmbox .foot {
padding: 6px;
color: #777;
}
.qmbox .font_darkblue {
color: #006699;
font-weight: bold;
}
.qmbox .font_lightblue {
color: #008BD1;
font-weight: bold;
}
.qmbox .font_gray {
color: #888;
font-size: 12px;
}
style>
<div class="contaner">
<div class="title">$(title)div>
<div class="content">
<p class="biaoti"><b>亲爱的用户,你好!b>p>
<b class="xtop"><b class="xb1">b><b class="xb2">b><b class="xb3">b><b class="xb4">b>b>
<div class="xboxcontent">
<div class="neirong">
<p><b>请核对你的用户名:b><span id="userName" class="font_darkblue">$(userName)span>p>
<p><b>$(type)的验证码:b><span class="font_lightblue"><span id="yzm" data="$(captcha)" onclick="return false;" t="7" style="border-bottom: 1px dashed rgb(204, 204, 204); z-index: 1; position: static;">$(captcha)span>span><br><span class="font_gray">(请输入该验证码完成$(type),验证码30分钟内有效!)span>p>
<div class="line">如果你未申请$(type)服务,请忽略该邮件。div>
div>
div>
<b class="xbottom"><b class="xb4">b><b class="xb3">b><b class="xb2">b><b class="xb1">b>b>
<p class="foot">如果仍有问题,请拨打我们的会员服务专线: <span data="800-820-5100" onclick="return false;" t="7" style="border-bottom: 1px dashed rgb(204, 204, 204); z-index: 1; position: static;">021-51875288
span>p>
div>
div>
<style type="text/css">
.qmbox style, .qmbox script, .qmbox head, .qmbox link, .qmbox meta {
display: none !important;
}
style>
div>
body>
html>
2 . 验证码生成工具类 CaptchaUtils.java
import java.util.Random;
public class CaptchaUtils {
/**
* Description:生成验证码
* @return
* @return String
* @author name:yuruixin
email: [email protected]
**/
public static String creatCaptcha(){
String captcha = captcha(6);
return captcha;
}
/**
* Description:生成随机数
* @param charCount
* @return
* @return String
* @author name:yuruixin
email: [email protected]
**/
public static String captcha(int charCount){
String charValue = "";
for (int i = 0; i < charCount; i++) {
char c = (char) (randomInt(0, 10) + '0');
charValue += String.valueOf(c);
}
return charValue;
}
public static int randomInt(int from, int to) {
Random r = new Random();
return from + r.nextInt(to - from);
}
}
3 . 邮件详情实体类 EmailMailInfo.java
/**
* ClassName: EmailMailInfo.java
* Description:
* Create by: name:yuxin
email: [email protected]
* Create Time: 2017年6月15日
*/
public class EmailMailInfo {
//邮箱服务器 如smtp.163.com
private String host ;
//用户邮箱 如**@163
private String formName ;
//用户授权码 不是用户名密码 可以自行查看相关邮件服务器怎么查看
private String formPassword ;
//消息回复邮箱
private String replayAddress ;
//发送地址
private String toAddress ;
//发送主题
private String subject ;
//发送内容
private String content ;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getFormName() {
return formName;
}
public void setFormName(String formName) {
this.formName = formName;
}
public String getFormPassword() {
return formPassword;
}
public void setFormPassword(String formPassword) {
this.formPassword = formPassword;
}
public String getReplayAddress() {
return replayAddress;
}
public void setReplayAddress(String replayAddress) {
this.replayAddress = replayAddress;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
4 . email模板加载与获取
/**
* ClassName: EmailTemplet.java
* Description:
* Create by: name:yuxin
email: [email protected]
* Create Time: 2017年6月15日
*/
public class EmailTemplet {
public static String getHtml(String title,String userName,String type,String captcha) {
String emailTemplet = System.getProperty("emailTemplet");
emailTemplet = emailTemplet.replace("$(title)", title);
emailTemplet = emailTemplet.replace("$(userName)", userName);
emailTemplet = emailTemplet.replace("$(type)", type);
emailTemplet = emailTemplet.replace("$(captcha)", captcha);
return emailTemplet;
}
/**
* Description:容器初始化是加载
* @return void
* @author name:yuxin
email: [email protected]
**/
public static void initEmailTemplet() {
String url = HospitalUtils.class.getResource("/emailTemplet.html")
.getFile();
url = url.substring(1, url.length());
try {
String encoding = "UTF-8";
File file = new File(url);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding);// 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
StringBuilder sb = new StringBuilder();
while ((lineTxt = bufferedReader.readLine()) != null) {
System.out.println(lineTxt);
sb.append(lineTxt);
}
System.setProperty("emailTemplet", sb.toString());
read.close();
} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
}
}
5 . 邮件发送工具类 EmailSendUtil.java
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EmailSendUtil {
private final static String host = "smtp.exmail.qq.com"; //163的服务器
private final static String formName = "[email protected]";//你的邮箱
private final static String password = "******"; //授权码
private final static String replayAddress = "[email protected]"; //你的邮箱
public static void sendHtmlMail(EmailMailInfo info)throws Exception{
info.setHost(host);
info.setFormName(formName);
info.setFormPassword(password); //网易邮箱的授权码~不一定是密码
info.setReplayAddress(replayAddress);
Message message = getMessage(info);
// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart html = new MimeBodyPart();
// 设置HTML内容
html.setContent(info.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
// 将MiniMultipart对象设置为邮件内容
message.setContent(mainPart);
Transport.send(message);
}
public static void sendTextMail(EmailMailInfo info) throws Exception {
info.setHost(host);
info.setFormName(formName);
info.setFormPassword(password); //网易邮箱的授权码~不一定是密码
info.setReplayAddress(replayAddress);
Message message = getMessage(info);
//消息发送的内容
message.setText(info.getContent());
Transport.send(message);
}
private static Message getMessage(EmailMailInfo info) throws Exception{
final Properties p = System.getProperties() ;
p.setProperty("mail.smtp.host", info.getHost());
p.setProperty("mail.smtp.auth", "true");
p.setProperty("mail.smtp.user", info.getFormName());
p.setProperty("mail.smtp.pass", info.getFormPassword());
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session session = Session.getInstance(p, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(p.getProperty("mail.smtp.user"),p.getProperty("mail.smtp.pass"));
}
});
session.setDebug(true);
Message message = new MimeMessage(session);
//消息发送的主题
message.setSubject(info.getSubject());
//接受消息的人
message.setReplyTo(InternetAddress.parse(info.getReplayAddress()));
//消息的发送者
message.setFrom(new InternetAddress(p.getProperty("mail.smtp.user"),"神鲸系统"));
// 创建邮件的接收者地址,并设置到邮件消息中
message.setRecipient(Message.RecipientType.TO,new InternetAddress(info.getToAddress()));
// 消息发送的时间
message.setSentDate(new Date());
return message ;
}
}
6 . 验证码发送邮件工具类 EMailUtil.java
import javax.servlet.http.HttpSession;
/**
* ClassName: EMailUtil.java
* Description:
* Create by: name:yuxin
email: [email protected]
* Create Time: 2017年6月15日
*/
public class EMailUtil {
/**
* Description:发送注册邮件
* @param email
* @param session
* @return
* @return String
* @author name:yuxin
email: [email protected]
**/
public static String sendForReg(String email,HttpSession session) {
String captcha = CaptchaUtils.creatCaptcha();
session.setAttribute("reg:"+email, captcha);
String title = "用户注册";
String content = EmailTemplet.getHtml(title, email, title, captcha);
EmailMailInfo info = new EmailMailInfo();
info.setToAddress(email);
info.setSubject(title);
info.setContent(content);
try {
// MailSendUtil.sendTextMail(info);
EmailSendUtil.sendHtmlMail(info);
} catch (Exception e) {
System.out.print("'" + title + "'的邮件发送失败!");
e.printStackTrace();
}
return captcha;
}
/**
* Description:发送密码重置邮件
* @param email
* @param session
* @return
* @return String
* @author name:yuxin
email: [email protected]
**/
public static String sendForResetPassword(String email,HttpSession session) {
String captcha = CaptchaUtils.creatCaptcha();
session.setAttribute("restPassword:"+email, captcha);
String title = "密码重置";
String content = EmailTemplet.getHtml(title, email, title, captcha);
EmailMailInfo info = new EmailMailInfo();
info.setToAddress(email);
info.setSubject(title);
info.setContent(content);
try {
// MailSendUtil.sendTextMail(info);
EmailSendUtil.sendHtmlMail(info);
} catch (Exception e) {
System.out.print("'" + title + "'的邮件发送失败!");
e.printStackTrace();
}
return captcha;
}
/**
* Description:校验验证码
* @param email
* @param captcha
* @param session
* @return
* @return boolean
* @author name:yuxin
email: [email protected]
**/
public static boolean checkCaptcha(String email,String type,String captcha,HttpSession session){
String captchaCache = null;
switch (type) {
case "reg":
captchaCache = (String) session.getAttribute("reg:"+email);
break;
case "restPassword":
captchaCache = (String) session.getAttribute("restPassword:"+email);
break;
default:
break;
}
if(captchaCache != null){
return captchaCache.equals(captcha);
}
return false;
}
}