把原作者的随机验证码改了一点,亲测可用
需要导入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";
}
}
}