目录
一、邮箱发送实现
1. 开通邮箱服务
使用qq邮箱、163邮箱都行,其他有邮箱服务功能的都可以,这里以163邮箱为例
登录163邮箱,然后在设置那里选择POP3/SMTP/IMAP
开通IMAP/SMTP服务
开通后会有个授权码,记录下来,后面需要用到
2. 添加邮箱依赖
添加pom文件
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
3.添加配置
host是开通smtp时会有个地址的
username填的是邮箱账号
password填的是刚才上面开通smtp的授权码
,请注意不是邮箱密码,是授权码
注:
1.配置里面有个port的配置是默认端口,尽量不要自己去设置,不然可能会无法访问,以下配置是没有port的
2.配置错误可以尝试把注释去掉,因为有可能会因为复制过去的编码问题影响
yaml
spring:
mail:
host: smtp.163.com # smtp地址,开通的时候会显示
username: xxxxx@163.com # 你的邮箱账号
password: ****** # 你的邮箱授权码
properties:
mail:
smtp:
auth: true
starttls:
enable: true
protocol: smtp
4.添加邮箱通用类
这里是用了hutools的工具和lombok的Slf4j日志,视情况而添加
xml
<!-- 工具类 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<scope>provided</scope>
</dependency>
java
@Service
@Slf4j
public class EmailService {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String username;
/**
* 发送文本邮件
*
* @param to 收件人地址
* @param subject 邮件主题
* @param content 邮件内容
* @param cc 抄送地址
*/
public void sendSimpleMail(String to, String subject, String content, String... cc) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(username);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
if (ArrayUtil.isNotEmpty(cc)) {
message.setCc(cc);
}
mailSender.send(message);
}
/**
* 发送HTML邮件
*
* @param to 收件人地址
* @param subject 邮件主题
* @param content 邮件内容
* @param cc 抄送地址
*/
public void sendHtmlMail(String to, String subject, String content, String... cc) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true,"UTF-8");
helper.setFrom(username);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
if (ArrayUtil.isNotEmpty(cc)) {
helper.setCc(cc);
}
mailSender.send(message);
} catch (MessagingException e) {
log.error("发送邮件失败,收件人:{}", to, e);
}
}
/**
* 发送带附件的邮件
*
* @param to 收件人地址
* @param subject 邮件主题
* @param content 邮件内容
* @param filePath 附件地址
* @param cc 抄送地址
*/
public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true,"UTF-8");
helper.setFrom(username);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
if (ArrayUtil.isNotEmpty(cc)) {
helper.setCc(cc);
}
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
mailSender.send(message);
} catch (MessagingException e) {
log.error("发送邮件失败,收件人:{}", to, e);
}
}
/**
* 发送正文中有静态资源的邮件
*
* @param to 收件人地址
* @param subject 邮件主题
* @param content 邮件内容
* @param rscPath 静态资源地址
* @param rscId 静态资源id
* @param cc 抄送地址
*/
public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId, String... cc) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true,"UTF-8");
helper.setFrom(username);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
if (ArrayUtil.isNotEmpty(cc)) {
helper.setCc(cc);
}
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);
mailSender.send(message);
} catch (MessagingException e) {
log.error("发送邮件失败,收件人:{}", to, e);
}
}
}
5. 测试类
java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes={EmailServiceApplication.class, EmailServiceTest.class})
public class EmailServiceTest {
@Resource
private EmailService emailService;
@Test
public void test(){
emailService.sendSimpleMail("1191986647@qq.com","测试","测试");
}
}
二、邮箱验证实现
实现验证需要使用redis,本章节不介绍如何使用redis,请自行搭建
1.添加依赖
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- jedis连接 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
2. 添加配置
yaml配置
yaml
spring:
redis:
host: localhost # redis地址
port: 6379
database: 0
password: 123456 # 密码,无密码可不填
序列化配置,新建一个config包,并添加RedisConfig类
java
@Configuration
public class RedisConfig {
@Bean
public StringRedisTemplate redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new StringRedisSerializer());
return template;
}
}
3.添加controller
java
@RestController
@RequestMapping("/api")
public class VerificationController {
@Autowired
private EmailService emailService;
@Autowired
private StringRedisTemplate redisTemplate;
@PostMapping("/sendCode")
public String sendCode(@RequestParam String email) {
// 生成验证码
String code = String.valueOf((int)((Math.random() * 9 + 1) * 100000));
emailService.sendHtmlMail(email, "【邮箱验证码】欢迎使用xxx系统", "<p>您的邮箱验证码是:<p><p style=\" font-weight: bold;text-align: center;color: red;\">"+code+"</p>" );
// 存储验证码到 Redis,设置过期时间为 5 分钟
ValueOperations<String, String> ops = redisTemplate.opsForValue();
redisTemplate.delete(email);
ops.set(email, code, 5, TimeUnit.MINUTES);
return "验证码已发送";
}
@PostMapping("/verifyCode")
public String verifyCode(@RequestParam String email, @RequestParam String code) {
// 从 Redis 获取验证码
ValueOperations<String, String> ops = redisTemplate.opsForValue();
String storedCode = ops.get(email);
if (storedCode != null && storedCode.equals(code)) {
redisTemplate.delete(email);
return "邮箱验证成功";
} else {
return "验证码错误或者已失效";
}
}
}
4. 测试
发送
验证