每天一篇之JAVA 邮箱验证两种方式
据我所知,java邮箱验证有两种方式,验证码、链接
这两种方式都涉及到发送邮件,首先实现发送邮件功能
首先申请邮箱号码,QQ邮箱要去申请发送邮件功能,阿里云邮箱不用,这个步骤我就不具体说了,
下面是一个简单发送邮件示例
首先配置pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
然后配置application.properties
spring.mail.host=smtp.qq.com //这个是QQ邮箱的 其他邮箱请另行百度
spring.mail.username=用户名 //发送方的邮箱
spring.mail.password=密码 //对于qq邮箱而言 密码指的就是发送方的授权码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
最后代码块
@RestController
@RequestMapping("/api/userCenter")
public class UserCenterController {
@Autowired
JavaMailSender jms;
//读取配置文件邮箱账号参数
@Value("${spring.mail.username}")
private String sender;
//发送待验证码的邮件
@RequestMapping("/sendEmail")
R sendEmail(@RequestParam(value = "email") @NotNull(message = "邮箱账号不能为空") @Pattern(regexp = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$", message = "邮箱不合法") String email) {
//随机数 用作验证
String code = RandomUtils.getRandomNum(6);
try {
//建立邮件消息
SimpleMailMessage mainMessage = new SimpleMailMessage();
//发送者
mainMessage.setFrom(sender);
//接收者
mainMessage.setTo(email);
//发送的标题
mainMessage.setSubject("邮箱验证");
//发送的内容
String msg = "您好!" + email + ",您正在使用邮箱验证,验证码:" + code + " ,有效时间为30分钟。";
mainMessage.setText(msg);
jms.send(mainMessage);
} catch (Exception e) {
throw new RRException("发送邮件失败,请核对邮箱账号", FAILE_CODE);
}
//下面是加入缓存,以便于进行邮箱验证
EhCacheUtil ehCacheUtil = new EhCacheUtil("email");
Element element = ehCacheUtil.getFromCache(String.valueOf(email));
ehCacheUtil.remove(email);
ehCacheUtil.putToCache(email, code);
R r = new R("邮件发送成功");
return r;
}
//验证邮箱验证码是否正确
@RequestMapping("/verifyEmail")
R verifyEmail(@RequestParam(value = "email") @NotNull(message = "邮箱不能为空") @Pattern(regexp = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$", message = "邮箱不合法") String email,
@RequestParam(value = "code") @NotNull(message = "验证码不能为空") String code) {
if (email.isEmpty()) {
throw new RRException(501, "邮箱不能为空");
}
if (code.isEmpty()) {
throw new RRException(502, "验证码不能为空");
}
R r;
EhCacheUtil ehCacheUtil = new EhCacheUtil("email");
Element element = ehCacheUtil.getFromCache(email);
if (element == null) {
throw new RRException(INVALID_PARAMA, "验证码无效或邮箱不正确");
} else {
if (System.currentTimeMillis() - element.getCreationTime() > 1800000) {
throw new RRException(FAILE_CODE, "验证码过期");
} else {
if (!code.equals(element.getObjectValue())) {
throw new RRException(FAILE_CODE, "验证码不正确");
} else {
customerService.setEmail(email);
ehCacheUtil.remove(email);
JSONObject jsonData = new JSONObject();
jsonData.put("email", email);
r = new R(SUCCESS_CODE, "验证成功");
r.setData(jsonData);
}
}
}
return r;
}
这就是验证码验证邮箱是否正确,