邮箱验证码功能实现

在进行实际项目的开发过程中,我们可能会遇到需要需要对用户账号密码进行找回,这时就需要我们通过邮件进行验证,从而对用户信息进行修改,下面我就将自己开发过程中的邮件发送功能简单描述一下,供大家学习使用。

1.MailSenderInfo是确定邮件发送的类型及其各种属性

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class MailSenderInfo {
	private String mailServerHost;      //发送邮件的服务器
	private String mailServerPort="587";    //发送邮件的服务器的端口
	private String fromAddress;            //发送者地址
	private String toAddress;              //接收者地址
	private String username;         //发送者用户名
	private String password;         //发送者密码
	private boolean validate=true;      //是否需要身份验证
	private String subject;           //邮件主题
	private String content;          //邮件内容
	private Map mailType;        //邮箱类型
	
	//得到邮件会话属性
		public Properties getProperties(){
			  Properties p = new Properties();
			  p.put("mail.smtp.host", this.mailServerHost);
			  p.put("mail.smtp.port", this.mailServerPort);
			  p.put("mail.smtp.auth", validate?"true":"false");
			  return p;
		}
		
		public String getMailServerHost() {
			return mailServerHost;
		}
		public void setMailServerHost(String mailServerHost) {
			this.mailServerHost = mailServerHost;
		}
		public String getMailServerPort() {
			return mailServerPort;
		}
		public void setMailServerPort(String mailServerPort) {
			this.mailServerPort = mailServerPort;
		}
		public String getFromAddress() {
			return fromAddress;
		}
		public void setFromAddress(String fromAddress) {
			this.fromAddress = fromAddress;
		}
		public String getToAddress() {
			return toAddress;
		}
		public void setToAddress(String toAddress) {
			this.toAddress = toAddress;
		}
		public String getUsername() {
			return username;
		}
		
		public void setUsername(String username) {
			this.username = username;
			this.fromAddress=username;
			if(username!=null&&username.length()>0){
			   String fromEmailExt=username.substring(username.lastIndexOf("@")+1,username.lastIndexOf("."));
			   this.mailServerHost=getMailType().get(fromEmailExt);
			}
		}
		
		public String getPassword() {
			return password;
		}
		public void setPassword(String password) {
			this.password = password;
		}
		public boolean isValidate() {
			return validate;
		}
		public void setValidate(boolean validate) {
			this.validate = validate;
		}
			 
		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;
		}
		public Map getMailType() {
			mailType=new HashMap();
			mailType.put("163","smtp.163.com");
			mailType.put("139","smtp.139.com");
			mailType.put("126","smtp.126.com");
			mailType.put("qq", "smtp.qq.com");
			mailType.put("sohu", "smtp.sohu.com");
			mailType.put("live","smtp.live.cn");
			mailType.put("msn","smtp.msn.com");
			mailType.put("kum", "mail.kum.Net.cn");
			mailType.put("hotmail","smtp.hotmail.cn");
			return mailType;
		}
		public void setMailType(Map mailType) {
			this.mailType = mailType;
		}
}

2.设置邮件发送者的基本信息

import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
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;
	//邮件发送器

import com.xidian.entity.MailSenderInfo;

public class MailSender {
	/**
	  * 根据邮件会话属性和密码验证器构造一个发送邮件的session    
	  * @return
	  */
	 protected  static Session getSession(MailSenderInfo mailSenderInfo){
	  if(mailSenderInfo == null){
	   return null;
	  }
	  MyAuthenticator authenticator = null;
	  Properties pro = mailSenderInfo.getProperties();
	  if(mailSenderInfo.isValidate()){
	   authenticator = new MyAuthenticator(mailSenderInfo.getUsername(),mailSenderInfo.getPassword());
	  }
	  return Session.getDefaultInstance(pro, authenticator);
	 }
	 
	 /**
	  * 发送文本格式邮件
	  * @return
	  */
	 public static boolean sendTextMail(MailSenderInfo mailSenderInfo){
		 try {
	        
			 //得到session
	         Session mailSession = getSession(mailSenderInfo); 
	         //根据session创建一个邮件消息
	         Message mailMessage=new MimeMessage(mailSession);
	   
	         //创建邮件发送者的地址
	         Address fromAddress=new InternetAddress(mailSenderInfo.getFromAddress());
	   
	         //创建邮件接收者的地址
	         Address toAddress=new InternetAddress(mailSenderInfo.getToAddress());
	   
	         //设置邮件发送者的地址
	         mailMessage.setFrom(fromAddress);
	   
	         //设置邮件接收者地址
	         mailMessage.setRecipient(Message.RecipientType.TO, toAddress);
	   
	         //设置邮件的主题
	         mailMessage.setSubject(mailSenderInfo.getSubject());
	   
	         //设置邮件的发送内容
	         mailMessage.setText(mailSenderInfo.getContent());
	   
	         //设置发送邮件的时间
	         mailMessage.setSentDate(new Date());
	   
	         //发送邮件
	         Transport.send(mailMessage);
	   
	         return true;
		 	} catch (Exception e) {
		 		e.printStackTrace();
		 		return false;
		 	}
	 }
	 
	 /**
	  * 发送html格式邮件
	  * @return
	  */
	 public static boolean sendHtmlMail(MailSenderInfo mailSenderInfo) {
		 try {
			 //得到session
			 Session mailSession = getSession(mailSenderInfo);
			 //根据session创建一个邮件消息
			 Message mailMessage = new MimeMessage(mailSession);
			 //创建邮件发送者的地址
			 Address fromAddress=new InternetAddress(mailSenderInfo.getFromAddress());
	   
			 //创建邮件接收者的地址
			 Address toAddress=new InternetAddress(mailSenderInfo.getToAddress());
	   
			 //设置邮件发送者的地址
			 mailMessage.setFrom(fromAddress);
	   
			 //设置邮件接收者地址
			 mailMessage.setRecipient(Message.RecipientType.TO, toAddress);
			 //设置邮件消息的主题
			 mailMessage.setSubject(mailSenderInfo.getSubject());
			 //设置邮件消息发送的时间
			 mailMessage.setSentDate(new Date());
			 //MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
			 Multipart mainPart = new MimeMultipart();
			 //创建一个包含HTML内容的MimeBodyPart
			 BodyPart html = new MimeBodyPart();
			 //设置HTML内容
			 html.setContent(mailSenderInfo.getContent(), "text/html; charset=UTF-8");
	   
			 //将内容添加到容器对象中
			 mainPart.addBodyPart(html);
			 //将MiniMultipart对象设置为邮件内容
			 mailMessage.setContent(mainPart);
			 //发送邮件
			 Transport.send(mailMessage);
	   
			 return true;
		 } catch (Exception e) {
			 e.printStackTrace();
			 return false;
		 }
	 }
}

3.MyAuthenticator 继承自Authenticator

import javax.mail.Authenticator;

import javax.mail.PasswordAuthentication;

public class MyAuthenticator  extends Authenticator{
	String userName = null;
	String password = null;
	 
	public MyAuthenticator(String userName, String password) {
		this.userName = userName;
		this.password = password;
	}
	
	@Override
	protected PasswordAuthentication getPasswordAuthentication() {
		
		return new PasswordAuthentication(userName, password);
	 }
}

4.SendEmaiServlet 是邮件发送的主入口,需要注意的是其中的用户名是用于发送邮件的邮箱账号,密码是经过第三方授权的,可以通过qq邮箱,163邮箱等在身份验证后免费获取。

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xidian.entity.Account;
import com.xidian.entity.MailSenderInfo;
import com.xidian.service.AccountService;
import com.xidian.service.impl.AccountServiceImpl;
import com.xidian.service.impl.MailSender;

public class SendEmailServlet  extends HttpServlet{
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		resp.setContentType("text/html;charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");
		req.setCharacterEncoding("UTF-8");
		MailSenderInfo senderInfo=new MailSenderInfo();
		String email = req.getParameter("email");
		AccountService as = new AccountServiceImpl();
		Account account = as.queryByEmail(email);
		if(account ==null){
			PrintWriter out = resp.getWriter();
			out.println("");
		}else{
			senderInfo.setUsername("[email protected]"); //用户名
			senderInfo.setPassword("xxxxxxxxxxxxxxxxx");      //密码
			senderInfo.setToAddress(email);//接收者
			senderInfo.setSubject("Battle邮箱验证"); //主题
			Random random = new Random();
//			int result=random.nextInt(10);
			String num = (int)(Math.random()*1000000)+"";
			String str ="您的暴雪游戏验证码为:"+num+",请保护好您的验证码安全不要告诉他人!";
			senderInfo.setContent(str); //内容
			//发送
			MailSender.sendHtmlMail(senderInfo);
			req.setAttribute("num", num);
			req.setAttribute("email", email);
			req.getRequestDispatcher("email.jsp").forward(req, resp);
		}
	}
}

你可能感兴趣的:(Java基础)