Java 发送邮箱验证码并在60秒内完成登录

把原作者的随机验证码改了一点,亲测可用

需要导入jar包 百度云分享链接 提取码: 376u

原作者链接


import java.util.Random;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class EmailUtil extends BaseController{
	
	
	// 随机验证码
	public String achieveCode() {  //由于数字1 和0 和字母 O,l 有时分不清,所有,没有字母1 、0
		String[] beforeShuffle= new String[] { "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
		"G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a",
		"b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
		"w", "x", "y", "z" };
		StringBuffer sb = new StringBuffer();
		Random rand=new Random();
		for (int i = 0; i < 4; i++) {
			sb.append(beforeShuffle[rand.nextInt(beforeShuffle.length)]); //随机获取4位
		}
		return sb.toString();
	}
	
	
	public  void sendAuthCodeEmail(String email, String authCode) {
		try {
	 	SimpleEmail mail = new SimpleEmail();
	 	mail.setHostName("smtp.163.com");//发送邮件的服务器
	 	mail.setAuthentication("填写自己的邮箱", "自己设置");//登录账号,SMTP的密码
	 	mail.setFrom("填写自己的邮箱","填写自己的邮箱");  //发送邮件的邮箱和发件人
	 	mail.setSSLOnConnect(true); //使用安全链接
	 	mail.addTo(email);//接收的邮箱
	 	mail.setSubject("xxx.验证码");//设置邮件的主题
		mail.setMsg("尊敬的用户:你好!\n xxx.验证码为:" + authCode+"\n"+"     (有效期为一分钟)");//设置邮件的内容
		mail.send();//发送
		} catch (EmailException e) {
			e.printStackTrace();
		}  
	}
	
	
	
	//发送验证码,并使用session存储设置值
	@RequestMapping("vcode")
	@ResponseBody
		public  String vcode(String email){
			 String code = new EmailUtil().achieveCode();  //生成随机密码
			 try {
				new EmailUtil().sendAuthCodeEmail(email,code);
		        session.setAttribute("Vcode", code);
		        session.setMaxInactiveInterval(60); //设置session有效期 60秒
		        return "ok";
			} catch (Exception e) {
				e.printStackTrace();
				return "no";
			}
		}
		
		
		//模拟登录  
		@RequestMapping("GetCode")
		@ResponseBody
		public String GetCode(String Code){
			
			System.out.println(session.getAttribute("Vcode"));
			
			if(Code.equals(session.getAttribute("Vcode"))){
				return "ok";
			}else{
				return "no";
			}
			
		}
		
		
}


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值