yml添加配置
#邮箱配置
mail:
host: smtp.qq.com #发送邮件服务器 qq的是smtp,其他的需要去度娘
username: 1@qq.com #发送者邮箱
password: jkntpjdjuklre #发送者邮箱授权码
protocol: smtp #发送邮件协议
properties.mail.smtp.auth: true #开启认证
properties.mail.smtp.port: 465 #设置端口465或者994
properties.mail.display.sendmail: aaa #可以任意
properties.mail.display.sendname: bbb #可以任意
#properties.mail.smtp.starttls.enable: true
properties.mail.smtp.starttls.required: true
properties.mail.smtp.ssl.enable: true #开启SSL
default-encoding: utf-8
#企业邮箱配置(这里以微信企业邮箱)
mail:
#host: smtp.lookroomnews.com #发送邮件服务器
host: smtp.exmail.qq.com #发送邮件服务器
username: s@lookroomnews.com #发送者邮箱
#password: jkntpjdjuklre #发送者邮箱授权码
password: 8dyYhRuQbfQux #发送者邮箱授权码
protocol: smtp #发送邮件协议
properties.mail.smtp.auth: true #开启认证
properties.mail.smtp.port: 465 #设置端口465或者994
properties.mail.display.sendmail: aaa #可以任意
properties.mail.display.sendname: bbb #可以任意
#properties.mail.smtp.starttls.enable: true
properties.mail.smtp.starttls.required: true
properties.mail.smtp.ssl.enable: true #开启SSL
default-encoding: utf-8
ServiceImpl
public class MailServiceImpl implements MailService {
//定义验证码
private Integer userVerificationCode = null;
@Autowired
JavaMailSender jms;
@Resource
private RedisCache redisCache;
@Resource
private MailMapper mailMapper;
@Resource
private JavaMailSender javaMailSender;
//读取配置文件邮箱账号参数
@Value("${spring.mail.username}")
private String sender;
@Override
public String sendMail(String email) {
Integer userVerificationCode = new Random().nextInt(999999);
log.info("生成验证码为:{}"+userVerificationCode);
try {
//建立邮件消息
SimpleMailMessage mainMessage = new SimpleMailMessage();
javaMailSender.send(message);
发送者邮箱(配置文件获取)
mainMessage.setFrom(sender);
接收者邮箱()
mainMessage.setTo(email);
发送的(邮箱)标题
mainMessage.setSubject("邮箱验证");
发送的内容
String msg = "您好!" + email + ",您正在使用邮箱验证,验证码:" + userVerificationCode + "。"+"http://localhost:端口号/app/mail/verify?authCode="+userVerificationCode;
//mainMessage.setText(msg,true);
发送邮件
jms.send(mainMessage);
} catch (Exception e) {
log.info("发送邮件失败:{}"+e);
return ("发送邮件失败,请核对邮箱账号");
}
//下面是加入缓存,以便于进行邮箱验证
redisCache.setCacheObject("code", String.valueOf(userVerificationCode), 60, TimeUnit.SECONDS);
return "验证码已经发送您的邮箱,请前去邮箱查看,验证码是:" + userVerificationCode ;
}
/*
*
* 邮箱验证码验证
* */
@Override
public String malVerify(String authCode) {
String code = redisCache.getCacheObject("code");//获取缓存
if (code == null){
return "验证码已失效,请重新发送邮件获取!";
}
log.info("redis缓存验证码和邮箱:{}"+code);
if (authCode.equals(code.substring(0, 6))){//取出缓存验证码
String email = code.substring(6);//取出缓存邮箱
//修改状态
mailMapper.updateStatus(email);
return "验证成功,请返回app进行登录!";
}
return "验证失败";
}