本篇主要描绘“发送邮箱验证码、session校验”相关前(html\js)后(java)台代码,业务逻辑示例,闲话少诉,直接上代码。
1、引入的jar包是mail-1.4.jar
2、java底层发送邮箱方法- public boolean sendEMail(Map<String, Object> map) {
- log.info("電子郵件接口執行開始!");
- String from = Cache.getInstance().getParamsConstant.EMAIL_FROM);
- String pwd = Cache.getInstance().getParams(Constant.EMAIL_PWD);
- String to = String.valueOf(map.get("mail"));
- String subject = String.valueOf(map.get("subject"));
- String content = String.valueOf(map.get("content"));
- String smtpHost = Cache.getInstance().getParams(Constant.EMAIL_SMTPHOST);
- if(StringUtils.isBlank(to) || StringUtils.isBlank(subject) || StringUtils.isBlank(content)){
- log.info("郵件地址("+to+")、主題("+subject+")、內容("+content+")有為空項,不符合發送條件");
- return false;
- }
- try{
- Properties props = new Properties();
- props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
- props.setProperty("mail.smtp.host", smtpHost); // 发件人的邮箱的 SMTP效劳器地址
- props.setProperty("mail.smtp.auth", "true"); // 恳求认证,参数名称与详细实现有关
- // 创建Session实例对象
- Session session = Session.getDefaultInstance(props);
- // 创建MimeMessage实例对象
- MimeMessage message = new MimeMessage(session);
- // 设置发件人
- message.setFrom(new InternetAddress(from));
- // 设置收件人
- message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
- // 设置发送日期
- message.setSentDate(new Date());
- // 设置邮件主题
- message.setSubject(subject);
- // 设置纯文本内容的邮件正文
- message.setText(content);
- // 保管并生成最终的邮件内容
- message.saveChanges();
- // 设置为debug形式, 可以查看详细的发送 log
- session.setDebug(true);
- // 获取Transport对象
- Transport transport = session.getTransport("smtp");
- // 第2个参数需要填写的是QQ邮箱的SMTP的受权码,什么是受权码,它又是如何设置?
- transport.connect(from, pwd);
- // 发送,message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
- transport.sendMessage(message, message.getAllRecipients());
- transport.close();
- }catch(Exception e){
- log.error(e.getMessage(), e);
- return false;
- }
- log.info("電子郵件接口執行完成,執行胜利!");
- return true;
- }
复制代码 3、java业务逻辑层调用发送邮箱、验证码加密存储在session中- @RequestMapping("/sendEMail.do")
- public void sendEMail(HttpServletRequest request, HttpServletResponse response) {
- String json = "{"success":false,"message":"操作失败","returnVal":""}";
- boolean res = false;//发送邮件标志
- Map<String, Object> map = new HashMap<String, Object>();
- try {
- String username = request.getParameter("username");
- User user = this.userService.findUserByLoginname(username);
- if(null == user){
- json = "{"success":false,"message":"无此人员","returnVal":""}";
- return;
- }
- //获取当前绑定邮箱地址
- String mail = user.getEmail();
- //验证邮箱地址
- if(StringUtils.isBlank(mail) || "null".equals(mail)){
- json = "{"success":false,"message":"当前用户尚未绑定邮箱","returnVal":""}";
- return;
- }
- //生成验证码
- String checkcode = Common.getCode();
- //发送验证码
- String _debug = Cache.getInstance().getParams(Constant.UIAS_DEBUG);
- if("1".equals(_debug)){//调试形式 不真发送 直接回显
- map.put("checkcode", checkcode);
- res = true;
- }else{//非调试形式 真实发送邮件
- //验证是否频繁发送验证码恳求 单位 秒
- String intervalTime = Cache.getInstance().getParams(Constant.EMAIL_INTERVAL_TIME);
- Object emailTimeFlag = request.getSession().getAttribute("emailTimeFlag");
- boolean checkTime = true;
- if (emailTimeFlag != null) {
- int miao = (int) (((new Date()).getTime() - (Long) emailTimeFlag) / 1000);
- if (miao <= Integer.parseInt(intervalTime)) {
- checkTime=false;
- }
- }
- if(checkTime){
- //组装数据
- String email_validity = Cache.getInstance().getParams(Constant.EMAIL_VALIDITY);
- String vartime= String.valueOf((Integer.parseInt(email_validity)/60000));
- String content = Cache.getInstance().getParams(Constant.EMAIL_CONTENT);
- String subject = Cache.getInstance().getParams(Constant.EMAIL_SUBJECT);
- content = content.replaceAll("\\$code", checkcode);
- content = content.replaceAll("\\$time",vartime);
- map.put("mail", mail);
- map.put("subject", subject);
- map.put("content", content);
- //调用发送
- res = ieMailService.sendEMail(map);
- }else{
- json = "{"success":false,"message":"请耐心等待,不要频繁发送验证码申请","returnVal":""}";
- return;
- }
- }
- //发送胜利后续操作
- if(res){
- //把验证时间放在session里
- request.getSession().setAttribute("emailTimeFlag", new Date().getTime());
- //把验证码放在session里 md5 2次加密验证码
- String codeMd5 = DigestUtils.md5Hex((DigestUtils.md5Hex(checkcode).toLowerCase()));
- request.getSession().setAttribute("emailCodeFlag", codeMd5);
- if("1".equals(_debug)){
- json = "{"success":true,"message":"邮箱验证码发送胜利,已经待填到验证码框!","returnVal":"","checkcode":""+checkcode+""}";
- }else{
- json = "{"success":true,"message":"邮箱验证码发送胜利,请查收邮件!","returnVal":""}";
- }
- }
- } catch (Exception e) {
- logger.error("发送邮件验证码异常", e);
- }finally{
- renderHtml(response, json, "encoding:UTF-8");
- }
- }
复制代码 4、java验证邮箱,比对session中的验证码和提交上来的验证码- @RequestMapping("/check.do")
- public void check(HttpServletRequest request, HttpServletResponse response) {
- String json = "{"success":false,"message":"操作失败","returnVal":""}";
- try {
- //验证码有效期校验
- String email_validity = Cache.getInstance().getParams(Constant.EMAIL_VALIDITY);
- Object emailTimeFlag = request.getSession().getAttribute("emailTimeFlag");
- if (emailTimeFlag != null) {
- int miao = (int) (((new Date()).getTime() - (Long) emailTimeFlag) / 1000);
- if (miao >= Integer.parseInt(email_validity)) {
- json = "{"success":false,"message":"验证码已过有效期,请重新获取!","returnVal":""}";
- }else{
- //在有效期内 比对验证码准确性
- String checkcode = request.getParameter("checkcode");
- // md5 2次加密验证码
- String codeMd5 = DigestUtils.md5Hex((DigestUtils.md5Hex(checkcode).toLowerCase()));
- Object emailCodeFlag = request.getSession().getAttribute("emailCodeFlag");
- boolean res = codeMd5.equals(String.valueOf(emailCodeFlag));
- if(res){
- json = "{"success":true,"message":"验证码通过!","returnVal":""}";
- }else{
- json = "{"success":false,"message":"验证码不匹配,请重新核对!","returnVal":""}";
- }
- }
- }
- } catch (Exception e) {
- logger.error("验证码异常", e);
- }finally{
- renderHtml(response, json, "encoding:UTF-8");
- }
- }
复制代码 5、小插曲,java处置要展示到页面的邮箱和手机号加*号隐藏的正则表达式- // 括号表示组,被交换的部分$n表示第n组的内容
- mail = mail.replaceAll("(\\w?)(\\w+)(\\w)(@\\w+\\.[a-z]+(\\.[a-z]+)?)", "$1****$3$4");
- // 括号表示组,被交换的部分$n表示第n组的内容
- phone = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
复制代码 6、HTML 获取验证码按钮 - <input id="btnMail" type="button" value="获取邮件验证码" />
复制代码 7、js 函数调用 按钮60秒倒计时- //获取邮箱验证码
- function start_mail_button(){
- var username = $('#username').val().trim();//用戶名
- if('' == username){
- ErrorMsg("请输入用户名");
- return;
- }
- $.ajax({
- url: basePath+'/sendEMail.do',type: 'post',dataType: 'json',
- data: {username: username},
- success: function(data){
- if(data.success){
- SuccMsg(data.message);
- //页面获取验证码按钮款式处置
- $("#btnMail").attr('disabled','disabled');
- var count = 1 ;
- var sum = 60;
- var i = setInterval(function(){
- if(count > 60){
- $("#btnMail").attr('disabled',false);
- $("#btnMail").val("获取邮箱验证码");
- clearInterval(i);
- }else{
- $("#btnMail").val("剩余"+parseInt(sum - count)+'秒');
- }
- count++;
- },1000);
- //debug形式待填
- if(data.checkcode){
- $("#checkcode").val(data.checkcode);
- }
- }else{
- ErrorMsg("获取失败!"+data.message);
- }
- }
- });
- }
复制代码 8、提交验证码的js没什么特别的,就不上代码了。
总结
以上所述是小编给大家介绍的Java发送邮箱验证码、session校验功能,希望对大家有所协助,假设大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感激大家对网站网站的支持! |