溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

SpringBoot使用郵箱發(fā)送驗(yàn)證碼實(shí)現(xiàn)注冊功能

發(fā)布時(shí)間:2020-09-17 02:38:11 來源:腳本之家 閱讀:429 作者:ForLevin 欄目:編程語言

本文為大家分享了SpringBoot使用郵箱發(fā)送驗(yàn)證碼實(shí)現(xiàn)注冊功能實(shí)例,供大家參考,具體內(nèi)容如下

這里有兩種方式:
使用Apache Common包中開源的email組件,通過實(shí)例化HtmlEmail()對象,可通過配置外置字典、或yml等配置文件實(shí)現(xiàn)靈活配置;

依賴:

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-email</artifactId>
  <version>1.5</version>
</dependency>

使用SpringBoot Starter email組件;

依賴:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

我這里是采用的第一種方式,簡單易懂;

首先需要配置Email的各項(xiàng)參數(shù),其中hostname、host、username、passsword(注意:此處的密碼并不是登錄的密碼,而是郵箱開啟smtp服務(wù)的令牌);
我這里使用SpringBoot的yml配置文件,可以通過切換不同的環(huán)境:local/dev/test/pro/prod等等環(huán)境實(shí)現(xiàn)靈活配置,該配置為自定義配置;

我此處使用的是本人的163郵箱,在實(shí)際開發(fā)中需要換為公司的或項(xiàng)目專用郵箱;
(注意:此種方式有缺陷,即為不能從外部進(jìn)行靈活配置,只能寫死配置文件,在實(shí)際使用上應(yīng)該配置為數(shù)據(jù)字典,可以在外部直接進(jìn)行靈活配置)

yml:

##Email配置
email:
 host-name: smtp.163.com #服務(wù)地址,可以直接在web端登錄,找到smtp服務(wù)看到,163郵箱默認(rèn)開放25端口,可暫時(shí)不設(shè)置
 authentication:
  username: xxx.163.com
  password: xxx #手動(dòng)的設(shè)置令牌
 form:
  mail: xxx@163.com #發(fā)送方,必須為你設(shè)置的username一致
  name: elog #發(fā)送方顯示的名稱,可以隨意設(shè)置
 charset: UTF-8 #編碼格式,一般設(shè)置為UTF-8

util:

package com.hisw.rest.utils;

import com.hisw.common.exception.RRException;
import org.apache.commons.mail.HtmlEmail;
/**
 * @ClassName EmailCodeUtils
 * @Description TODO 郵箱驗(yàn)證碼工具類
 * @Author liwenju
 * @Date 2019/5/15 14:20
 * @Version 1.0
 **/
public class EmailCodeUtils {

  /**
   * 生成6位隨機(jī)驗(yàn)證碼
   * @return
   */
  public static String getNumber(){
    String str = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    String code = "";
    for(int i= 0;i<6;i++){
      int index = (int)(Math.random()*str.length());
      code+=str.charAt(index);
    }
    return code;
  }

  /**
   * 發(fā)送郵箱驗(yàn)證碼
   * @param receiverEmail
   * @param subject
   * @param msg
   */
  public static void sendEmailCode(String EMAIL_HOST_NAME,String EMAIL_FORM_MAIL,
               String EMAIL_FORM_NAME,String EMAIL_AUTHENTICATION_USERNAME,
               String EMAIL_AUTHENTICATION_PASSWORD,String receiverEmail,
               String subject,String msg){
    try{
      HtmlEmail email = new HtmlEmail();
      email.setHostName(EMAIL_HOST_NAME);
      email.setCharset("utf-8");
      email.setFrom(EMAIL_FORM_MAIL,EMAIL_FORM_NAME);
      email.setAuthentication(EMAIL_AUTHENTICATION_USERNAME,EMAIL_AUTHENTICATION_PASSWORD);
      email.addTo(receiverEmail);
      email.setSubject(subject);
      email.setMsg(msg);
      email.send();
    }catch (Exception ex){
      throw new Exception("發(fā)送驗(yàn)證碼失敗,原因:"+ex.getMessage());
    }
  }

}

注意:在靜態(tài)工具類的方法中,不可直接調(diào)用@Value(value="$xxx")來獲取yml的配置文件的參數(shù)值,否則會(huì)獲取不到值。故不在該util類中直獲取。如下所示:

/**
 * 獲取郵箱配置
 */
@Value(value = "${email.host-name}")
public String EMAIL_HOST_NAME;

方法示例:

/**
 * 獲取郵箱配置
 */
@Value(value = "${email.host-name}")
public String EMAIL_HOST_NAME;

@Value(value = "${email.authentication.username}")
public String EMAIL_AUTHENTICATION_USERNAME;

@Value(value = "${email.authentication.password}")
public String EMAIL_AUTHENTICATION_PASSWORD;

@Value(value = "${email.charset}")
public String EMAIL_CHARSET;

@Value(value = "${email.form.mail}")
public String EMAIL_FORM_MAIL;

@Value(value = "${email.form.name}")
public String EMAIL_FORM_NAME;

@Autowired
private SysUserDao sysUserDao;

@Autowired
private SysUserTokenDao sysUserTokenDao;

@Autowired
private RedisUtils redisUtils;

private Logger logger = LoggerFactory.getLogger(LoginUserServiceImpl.class);
/**
 * 驗(yàn)證碼過期時(shí)間60s
 */
private Integer redisExpire = 60 * 1000;

/***
 * 根據(jù)郵箱驗(yàn)證用戶
 * @param account
 * @return
 */
public SysUserEntity queryByEmail(String account){
  SysUserEntity sysUserEntity = new SysUserEntity();
  sysUserEntity.setEmail(account);
  return sysUserDao.selectOne(sysUserEntity);
}

/**
 * 判斷該郵箱是否已存在
 * @param email
 * @return
 */
public Boolean checkEmail(String email){
  //首先判斷該用戶是否已存在
  if (StringUtils.isNotEmpty(email)){
    EntityWrapper<SysUserEntity> userEntityWrapper = new EntityWrapper<>();
    userEntityWrapper.eq("email",email);
    List<SysUserEntity> sysUserList = sysUserDao.selectList(userEntityWrapper);
    //如果已存在該用戶
    return sysUserList.size() <= 0;
  }
  return true;
}

/**
 *發(fā)送郵箱驗(yàn)證碼
 *
 */
public R sendRegisterEmailCode(String email) {
  try {
    //驗(yàn)證郵箱規(guī)則
    if (!RegexUtils.checkEmail(email)){
      throw new RRException("The mailbox does not conform to the specification!");
    }
    if (!checkEmail(email)){
      throw new RRException("This mailbox already exists. Please change the user's email and try again!");
    }
    String emailCode = EmailCodeUtils.getNumber();
    //發(fā)送驗(yàn)證碼
    EmailCodeUtils.sendEmailCode(EMAIL_HOST_NAME, EMAIL_FORM_MAIL,
        EMAIL_FORM_NAME, EMAIL_AUTHENTICATION_USERNAME,
        EMAIL_AUTHENTICATION_PASSWORD, email, EmailTextTemplate.REGISTER_SUBJECT,
        EmailTextTemplate.REGISTER_CONTENT + emailCode + EmailTextTemplate.CONTENT_SUFFIX);
    logger.info("驗(yàn)證碼發(fā)送成功:{}", email);
    //發(fā)送成功,將該驗(yàn)證碼按照規(guī)定格式放入redis
    redisUtils.set(RestRedisConstant.REST_ELOG_REGISTER_EMAIL_CODE_KEY + email, emailCode, redisExpire);
    logger.info("Redis存儲(chǔ)驗(yàn)證碼成功:{}", emailCode);
    return R.ok("The verification code has been sent to your mailbox and is valid for 60 seconds.");
  } catch (Exception ex) {
    return R.error(ex.getMessage());
  }
}


/**
 *驗(yàn)證驗(yàn)證碼
 /
 public R checkRegisterEmailCode(String email, String code) {
  try {
    String redisCode = redisUtils.get(RestRedisConstant.REST_ELOG_REGISTER_EMAIL_CODE_KEY+email);
    //判斷是否已過期
    if (StringUtils.isEmpty(redisCode)){
      return R.error("The E-mail verification code has expired, please try again.");
    }
    //判斷驗(yàn)證碼是否正確
    if (!StringUtils.equals(redisCode,code)){
      return R.error("The E-mail verification code is wrong. Please try again.");
    }
    //驗(yàn)證成功,從redis中移除該key&value
    redisUtils.delete(RestRedisConstant.REST_ELOG_REGISTER_EMAIL_CODE_KEY+email);
    return R.ok("The E-mail verification code has been verified.");
  }catch (Exception ex){
    throw new RRException(ex.getMessage());
  }
}

說明:R.error (msg)/ throw new RRExcepion(msg)中,msg應(yīng)該以enum或常量的方式組織起來;
在發(fā)送驗(yàn)證碼、校驗(yàn)驗(yàn)證碼時(shí),應(yīng)該有一個(gè)工具類,驗(yàn)證一個(gè)郵箱在特定的短時(shí)間內(nèi)只能發(fā)送或驗(yàn)證幾次驗(yàn)證碼,超過此限制,應(yīng)該拒絕處理請求;

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI