1、我们需要登录邮箱开通邮箱授权码
2、然后需要pom需要引入spring-boot-starter-mail
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.6.4</version>
</dependency>
需要在配置文件 application.properties里面添加
<!-- 邮箱验证 -->
#163邮箱
spring.mail.host=smtp.163.com
#这里配置你的邮箱
spring.mail.username=XXX@163.com
spring.mail.password=开启smtp时候的授权码
spring.mail.default-encoding=utf-8
spring.mail.port=465
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
如果这里指定465端口,该端口和项目服务端口不冲突。邮件发送协议必须是smtps 不指定发送邮件时会报错,所以必须指定protocol配置为smtps
逻辑代码
上边pom的spring-boot-starter-mail引入后你能使用
JavaMailSender 是mail包提供的
package com.qiyuan.qyframe.base.service;
import com.qiyuan.qyframe.base.common.BusiException;
import com.qiyuan.qyframe.base.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Random;
@Slf4j
@Service
public class EmailService {
@Value("${spring.mail.host}")
private String host;
@Value("${spring.mail.username}")
private String username;
@Value("${spring.mail.password}")
private String password;
@Autowired
private RedisUtil redisUtil;
@Autowired
private JavaMailSender sender;
public void sendEmailCode(String email) {
if (StringUtils.isBlank(email)) {
throw new BusiException("请输入正确的邮箱账号");
}
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(username);
message.setTo(email);
message.setSubject("验证码");
String verificationCode = String.valueOf(new Random().nextInt(899999) + 100000);
//System.out.println(verificationCode);
message.setText("尊敬的用户你好,你所收到的验证码: " + verificationCode);
sender.send(message);
//将验证码放入Redis中,并定时五分钟,五分钟后删除
redisUtil.set(email, verificationCode, 5 * 60);
}
}
然后你就可以在你的业务代码中调上边封装的EmailService了
@AnonymousAccess
@RequestMapping(value = "/emailCode", method = RequestMethod.POST)
public ResponseData emailCode(String email) {
String errMsg = "";
try {
emailService.sendEmailCode(email);
} catch (BusiException e) {
errMsg = e.getMessage();
log.error("PhoneCodeController-emailCode occur BusiException", e);
return ResponseDataUtil.buildSuccess(ResultEnums.ERROR.getCode(), errMsg);
} catch (Exception e) {
//异常信息
errMsg = "系统错误";
log.error("PhoneCodeController-emailCode occur Exception", e);
return ResponseDataUtil.buildSuccess(ResultEnums.ERROR.getCode(), errMsg);
}
return ResponseDataUtil.buildSuccess(ResultEnums.SUCCESS.getCode(), "操作成功");
}
流程大概就这些啦,应该没啥问题了,搞定