SPRING BOOT邮件发送验证码
一、Gmail邮箱配置
1、进入Gmail(https://mail.google.com)
2、打开谷歌右上角设置
3、启用POP/IMP
4、启用两步验证(https://myaccount.google.com/security)
5、建立应用程式密码
6、复制保存应用程式密码
二、代码
1、引入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>
2、application.properties文件配置
spring.mail.host=smtp.gmail.com
# 邮件服务器端口号
spring.mail.port=587
# 邮件发送方的电子邮件地址
spring.mail.username=你的Gmail邮箱账号
# 邮件发送方的密码或应用程序专用密码(如果启用了两步验证)
spring.mail.password=应用程序专用密码
# 启用TLS加密
spring.mail.properties.mail.smtp.starttls.enable=true
# 验证邮件服务器的身份
spring.mail.properties.mail.smtp.auth=true
# 邮件传输协议
spring.mail.properties.mail.transport.protocol=smtp
3、EmailUtil邮件工具类
@Service
public class EmailUtil implements EmailService
{private final Logger logger = LoggerFactory.getLogger(this.getClass());//Spring Boot 提供了一个发送邮件的简单抽象,使用的是下面这个接口,这里直接注入即可使用@Autowiredprivate JavaMailSender mailSender;// 配置文件中我的谷歌邮箱@Value("${spring.mail.username}")private String from;/*** 简单文本邮件* @param to 收件人* @param subject 主题* @param content 内容*/@Overridepublic void sendSimpleMail(String to, String subject, String content) {//创建SimpleMailMessage对象SimpleMailMessage message = new SimpleMailMessage();//邮件发送人message.setFrom(from);//邮件接收人message.setTo(to);//邮件主题message.setSubject(subject);//邮件内容message.setText(content);//发送邮件mailSender.send(message);}/*** html邮件* @param to 收件人,多个时参数形式 :"xxx@xxx.com,xxx@xxx.com,xxx@xxx.com"* @param subject 主题* @param content 内容*/@Overridepublic void sendHtmlMail(String to, String subject, String content) {//获取MimeMessage对象MimeMessage message = mailSender.createMimeMessage();MimeMessageHelper messageHelper;try {messageHelper = new MimeMessageHelper(message, true);//邮件发送人messageHelper.setFrom(from);//邮件接收人,设置多个收件人地址InternetAddress[] internetAddressTo = InternetAddress.parse(to);messageHelper.setTo(internetAddressTo);//messageHelper.setTo(to);//邮件主题message.setSubject(subject);//邮件内容,html格式messageHelper.setText(content, true);//发送mailSender.send(message);//日志信息logger.info("邮件已经发送。");} catch (Exception e) {logger.error("发送邮件时发生异常!", e);}}/*** 带附件的邮件* @param to 收件人* @param subject 主题* @param content 内容* @param filePath 附件*/@Overridepublic void sendAttachmentsMail(String to, String subject, String content, String filePath) {MimeMessage message = mailSender.createMimeMessage();try {MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setFrom(from);helper.setTo(to);helper.setSubject(subject);helper.setText(content, true);FileSystemResource file = new FileSystemResource(new File(filePath));String fileName = filePath.substring(filePath.lastIndexOf(File.separator));helper.addAttachment(fileName, file);mailSender.send(message);//日志信息logger.info("邮件已经发送。");} catch (Exception e) {logger.error("发送邮件时发生异常!", e);}}/*** 验证邮箱格式* @param email* @return*/public boolean isEmail(String email) {if (email == null || email.length() < 1 || email.length() > 256) {return false;}Pattern pattern = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");return pattern.matcher(email).matches();}
}
EmailService
public interface EmailService {/*** 发送文本邮件** @param to 收件人* @param subject 主题* @param content 内容*/void sendSimpleMail(String to, String subject, String content);/*** 发送HTML邮件** @param to 收件人* @param subject 主题* @param content 内容*/public void sendHtmlMail(String to, String subject, String content);/*** 发送带附件的邮件** @param to 收件人* @param subject 主题* @param content 内容* @param filePath 附件*/public void sendAttachmentsMail(String to, String subject, String content, String filePath);
}
4、验证码存储/判断/删除
CodeUtil
@Service
public class CodeUtil {@Autowiredprivate StringRedisTemplate redisTemplate;public String generateVerificationCode() {// 生成6位随机数字验证码return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));}// 验证验证码是否正确public boolean verifyCode(String userId, String code,String key) {key = key + userId;String storedCode = redisTemplate.opsForValue().get(key);return code.equals(storedCode);}//删除redis中验证码public void deleteCode(String userId,String key) {key = key + userId;redisTemplate.delete(key);}
}
存储验证码
//写在需要发送验证码的地方//存储时间private static final int EXPIRATION_TIME_IN_MINUTES = 3;//键名private static final String KEY_PREFIX =="xxx";key=KEY_PREFIX+"123456"
redisTemplate.opsForValue().set(key, 随机数字验证码, EXPIRATION_TIME_IN_MINUTES, TimeUnit.MINUTES);