SpringBoot实现 QQ邮箱验证码
文章目录
SpringBoot实现 QQ邮箱验证码 一、开通SMTP校验码 1.登录qq邮箱 2.开启SMTP服务 3.发送手机短信 4.得到授权码
二、回到spring项目中 1.导入所需依赖 2.验证码工具类 3.具体实现逻辑(serviceimpl)
三、测试qq邮箱验证码
一、开通SMTP校验码
1.登录qq邮箱
2.开启SMTP服务
3.发送手机短信
4.得到授权码
二、回到spring项目中
1.导入所需依赖
< ! -- 邮箱验证登录导入的依赖-- >
< dependency>
< groupId> javax. activation< / groupId>
< artifactId> activation< / artifactId>
< version> 1.1 .1 < / version>
< / dependency>
< dependency>
< groupId> org. apache. commons< / groupId>
< artifactId> commons- email< / artifactId>
< version> 1.4 < / version>
< / dependency>
< dependency>
< groupId> javax. mail< / groupId>
< artifactId> mail< / artifactId>
< version> 1.4 .1 < / version>
< / dependency>
< dependency>
< groupId> io. github. openfeign< / groupId>
< artifactId> feign- core< / artifactId>
< / dependency>
2.验证码工具类
public class ValidateCodeUtils {
public static String generateValidateCode ( int length) {
String code = "" ;
Random random = new Random ( ) ;
for ( int i = 0 ; i < length; i++ ) {
int type = random. nextInt ( 3 ) ;
switch ( type) {
case 0 :
code += ( char ) ( random. nextInt ( 10 ) + '0' ) ;
break ;
case 1 :
code += ( char ) ( random. nextInt ( 26 ) + 'A' ) ;
break ;
case 2 :
code += ( char ) ( random. nextInt ( 26 ) + 'a' ) ;
break ;
}
}
return code;
}
public static String generateValidateCode4String ( int length) {
Random rdm = new Random ( ) ;
String hash1 = Integer . toHexString ( rdm. nextInt ( ) ) ;
String capstr = hash1. substring ( 0 , length) ;
return capstr;
}
}
public class EmailUtil {
public static void sendAuthCodeEmail ( String email, String authCode) {
try {
SimpleEmail mail = new SimpleEmail ( ) ;
mail. setHostName ( "smtp.qq.com" ) ;
mail. setAuthentication ( "xxx@qq.com" , "xxx" ) ;
mail. setFrom ( "xxx@qq.com" , "xxx" ) ;
mail. setSSLOnConnect ( true ) ;
mail. addTo ( email) ;
mail. setSubject ( "xxx验证码" ) ;
mail. setMsg ( "尊敬的用户您好,\n\n感谢您选择我们的服务!您的登录验证码为:" + "[" + authCode+ "]" + ",请妥善保管。请注意,该验证码仅在三分钟内有效,请尽快使用。\n\n若有任何疑问,请随时联系我们。祝您生活愉快" ) ;
mail. send ( ) ;
} catch ( EmailException e) {
e. printStackTrace ( ) ;
}
}
}
3.具体实现逻辑(serviceimpl)
@Override
public ResponseResult sendEmail ( String msg) {
if ( StringUtils . isNotEmpty ( msg) ) {
String code = ValidateCodeUtils . generateValidateCode ( 6 ) . toString ( ) ;
logger. info ( "验证码code:" + code) ;
EmailUtil . sendAuthCodeEmail ( msg, code) ;
redisTemplate. opsForValue ( ) . set ( msg , code, 3 , TimeUnit . MINUTES ) ;
return new ResponseResult ( 200 , "发送成功" , code) ;
}
return new ResponseResult ( 410 , "发送失败" , null ) ;
}
三、测试qq邮箱验证码