大坑
一定要先下jar包,javax.mail的jar包 jar包链接
思路分析
1.申请邮箱
2.开启授权码(登录邮箱设置SMTP/POP3等等协议)
3.在项目的MailUtils中设置自己的账号和密码(授权码)
MailUtil工具类
package com.lcx.util;import java.util.Properties;import javax.mail.Authenticator;import javax.mail.Message;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;/** * @author 作者 E-mail: * @version 创建时间:5月18日 下午9:44:28 * 类说明 邮件激活 发送邮件*/public final class MailUtil {private static final String USER="xxxxxxx@";//邮箱地址private static final String PASSWORD="xxxxxxx";//邮箱授权码public static boolean sendMail(String to,String text,String title) {try {final Properties pro = new Properties();pro.put("mail.smtp.auth","true");pro.put("mail.smtp.host","");//发件人账号pro.put("mail.user",USER);pro.put("mail.password",PASSWORD);//授权信息Authenticator authenticator = new Authenticator() {protected PasswordAuthentication getPasswordAuthentication() {//用户名,密码String username=pro.getProperty("mail.user");String password=pro.getProperty("mail.password");return new PasswordAuthentication(username,password);} };//使用环境属性和授权信息,创建邮件会话Session mailSession=Session.getInstance(pro,authenticator);//创建邮件消息MimeMessage message=new MimeMessage(mailSession);//设置发件人String username=pro.getProperty("mail.user");InternetAddress form = new InternetAddress(username);message.setFrom(form);InternetAddress toAddress = new InternetAddress(to);message.setRecipient(Message.RecipientType.TO,toAddress);//设置邮件标题message.setSubject(title);//设置邮件的内容message.setContent(text,"text/html;charset=UTF-8");Transport.send(message);return true;}catch(Exception e) {e.printStackTrace();}return false;}}
接下来就是调用了,在用户注册填写信息,点击提交后,就可以走流程了。
对用户的表示是验证的激活码,跟在连接后面的,唯一表示,这里使用java自带的Uuid包生成
简单写一个生成随机激活码的工具类吧,方便日后调用,就两行
package com.lcx.util;import java.util.UUID;/** * @author 作者 E-mail: * @version 创建时间:5月19日 下午8:30:22 * 类说明 生成随机的激活码*/public final class UuidUtil {private UuidUtil() {}public static String getUuid() {return UUID.randomUUID().toString().replace("-", ".");}}
以上就是主要的的代码了,接下来就是在需要实现功能的方法只调用
我这里是注册时需要邮箱验证,所以需要在注册的实现方法中调用方法
因为用户验证时需要点击激活,激活码是唯一标识,所以需要在User对象中设置激活码和标记是否激活
public int register(User user) {// TODO Auto-generated method stub//满足要求的信息,先设置激活码user.setCode(UuidUtil.getUuid());//设置激活状态user.setStatus("n");//写入数据库//发送激活邮件,要用绝对路径String content= "<a href='http://localhost/SSM_Springmvc_pra/active?code="+user.getCode()+"'>点击激活</a>";//发送邮件MailUtil.sendMail(user.getEmail(), content, "验证邮件");return dao.register(user);}
贴一张初步实现邮件发送的图
接下来就是要实现用户点击邮箱连接,实现激活的功能了。在用户点击连接后,后台更具code查找用户对象,修改用户对象的激活状态即可。