目录
- 一、邮箱发送实现
- 1. 开通邮箱服务
- 2. 添加邮箱依赖
- 3.添加配置
- 4.添加邮箱通用类
- 5. 测试类
- 二、邮箱验证实现
- 1.添加依赖
- 2. 添加配置
- 3.添加controller
- 4. 测试
项目地址: https://gitee.com/nssnail/springboot-email
一、邮箱发送实现
1. 开通邮箱服务
使用qq邮箱、163邮箱都行,其他有邮箱服务功能的都可以,这里以163邮箱为例
登录163邮箱,然后在设置那里选择POP3/SMTP/IMAP
开通IMAP/SMTP服务
开通后会有个授权码,记录下来,后面需要用到
2. 添加邮箱依赖
添加pom文件
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId>
</dependency>
3.添加配置
host是开通smtp时会有个地址的
username填的是邮箱账号
password填的是刚才上面开通smtp的授权码
,请注意不是邮箱密码,是授权码
注:
1.配置里面有个port的配置是默认端口,尽量不要自己去设置,不然可能会无法访问,以下配置是没有port的
2.配置错误可以尝试把注释去掉,因为有可能会因为复制过去的编码问题影响
spring:mail:host: smtp.163.com # smtp地址,开通的时候会显示username: xxxxx@163.com # 你的邮箱账号password: ****** # 你的邮箱授权码properties:mail:smtp:auth: truestarttls:enable: trueprotocol: smtp
4.添加邮箱通用类
这里是用了hutools的工具和lombok的Slf4j日志,视情况而添加
<!-- 工具类 -->
<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>
@Service
@Slf4j
public class EmailService {@Autowiredprivate 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. 测试类
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes={EmailServiceApplication.class, EmailServiceTest.class})
public class EmailServiceTest {@Resourceprivate EmailService emailService;@Testpublic void test(){emailService.sendSimpleMail("1191986647@qq.com","测试","测试");}
}
二、邮箱验证实现
实现验证需要使用redis,本章节不介绍如何使用redis,请自行搭建
1.添加依赖
<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配置
spring:redis:host: localhost # redis地址port: 6379database: 0 password: 123456 # 密码,无密码可不填
序列化配置,新建一个config包,并添加RedisConfig类
@Configuration
public class RedisConfig {@Beanpublic StringRedisTemplate redisTemplate(RedisConnectionFactory factory) {StringRedisTemplate template = new StringRedisTemplate(factory);template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(new StringRedisSerializer());return template;}
}
3.添加controller
@RestController
@RequestMapping("/api")
public class VerificationController {@Autowiredprivate EmailService emailService;@Autowiredprivate 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. 测试
发送
验证