您好,登錄后才能下訂單哦!
本文為大家分享了SpringBoot使用郵箱發送驗證碼實現注冊功能實例,供大家參考,具體內容如下
這里有兩種方式:
使用Apache Common包中開源的email組件,通過實例化HtmlEmail()對象,可通過配置外置字典、或yml等配置文件實現靈活配置;
依賴:
<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的各項參數,其中hostname、host、username、passsword(注意:此處的密碼并不是登錄的密碼,而是郵箱開啟smtp服務的令牌);
我這里使用SpringBoot的yml配置文件,可以通過切換不同的環境:local/dev/test/pro/prod等等環境實現靈活配置,該配置為自定義配置;
我此處使用的是本人的163郵箱,在實際開發中需要換為公司的或項目專用郵箱;
(注意:此種方式有缺陷,即為不能從外部進行靈活配置,只能寫死配置文件,在實際使用上應該配置為數據字典,可以在外部直接進行靈活配置)
yml:
##Email配置 email: host-name: smtp.163.com #服務地址,可以直接在web端登錄,找到smtp服務看到,163郵箱默認開放25端口,可暫時不設置 authentication: username: xxx.163.com password: xxx #手動的設置令牌 form: mail: xxx@163.com #發送方,必須為你設置的username一致 name: elog #發送方顯示的名稱,可以隨意設置 charset: UTF-8 #編碼格式,一般設置為UTF-8
util:
package com.hisw.rest.utils; import com.hisw.common.exception.RRException; import org.apache.commons.mail.HtmlEmail; /** * @ClassName EmailCodeUtils * @Description TODO 郵箱驗證碼工具類 * @Author liwenju * @Date 2019/5/15 14:20 * @Version 1.0 **/ public class EmailCodeUtils { /** * 生成6位隨機驗證碼 * @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; } /** * 發送郵箱驗證碼 * @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("發送驗證碼失敗,原因:"+ex.getMessage()); } } }
注意:在靜態工具類的方法中,不可直接調用@Value(value="$xxx")來獲取yml的配置文件的參數值,否則會獲取不到值。故不在該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); /** * 驗證碼過期時間60s */ private Integer redisExpire = 60 * 1000; /*** * 根據郵箱驗證用戶 * @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; } /** *發送郵箱驗證碼 * */ public R sendRegisterEmailCode(String email) { try { //驗證郵箱規則 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(); //發送驗證碼 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("驗證碼發送成功:{}", email); //發送成功,將該驗證碼按照規定格式放入redis redisUtils.set(RestRedisConstant.REST_ELOG_REGISTER_EMAIL_CODE_KEY + email, emailCode, redisExpire); logger.info("Redis存儲驗證碼成功:{}", 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()); } } /** *驗證驗證碼 / 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."); } //判斷驗證碼是否正確 if (!StringUtils.equals(redisCode,code)){ return R.error("The E-mail verification code is wrong. Please try again."); } //驗證成功,從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應該以enum或常量的方式組織起來;
在發送驗證碼、校驗驗證碼時,應該有一個工具類,驗證一個郵箱在特定的短時間內只能發送或驗證幾次驗證碼,超過此限制,應該拒絕處理請求;
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。