当前位置: 首页 > news >正文

JavaMail的使用

1. 项目配置

1.1 Spring Boot 配置

在 application.properties 中可以配置 Spring Boot 应用的各种属性,例如邮件服务、数据库连接等。

spring.mail.host=smtp.qq.com
spring.mail.port=587
spring.mail.username=6666666666@qq.com
spring.mail.password= #SMTP 相关的认证
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
1.2 跨域配置(CorsConfig.java)

通过 CorsConfig 类配置跨域访问,允许所有来源、所有请求头和所有请求方法的跨域请求,并允许携带凭证:

@Configuration
public class CorsConfig {@Beanpublic CorsFilter corsFilter() {CorsConfiguration config = new CorsConfiguration();config.addAllowedOriginPattern("*");config.addAllowedHeader("*");config.addAllowedMethod("*");config.setAllowCredentials(true);UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", config);return new CorsFilter(source);}
}

2. 服务接口定义

EmailService 接口定义了发送验证码和验证验证码的方法:

import com.example.house.Utils.Result;public interface EmailService {Result<String> sendVerificationCode(String email);Result<Boolean> verifyVerificationCode(String email, String code);
}

3. 服务实现类

EmailServiceImpl 类实现了 EmailService 接口,具体实现了发送和验证验证码的逻辑:

import com.example.house.Service.EmailService;
import com.example.house.Utils.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;import java.util.HashMap;
import java.util.Map;
import java.util.Random;@Service
public class EmailServiceImpl implements EmailService {private final JavaMailSender javaMailSender;@Value("${spring.mail.username}")private String from;private static final Map<String, String> verificationCodes = new HashMap<>();public EmailServiceImpl(JavaMailSender javaMailSender) {this.javaMailSender = javaMailSender;}@Overridepublic Result<String> sendVerificationCode(String email) {try {String code = generateVerificationCode();verificationCodes.put(email, code);SimpleMailMessage message = new SimpleMailMessage();message.setFrom(from);message.setTo(email);message.setSubject("注册验证码");message.setText("您的注册验证码是:" + code);javaMailSender.send(message);return Result.success("验证码已发送,请查收邮件");} catch (Exception e) {e.printStackTrace();return Result.fail(500, "发送验证码失败:" + e.getMessage());}}@Overridepublic Result<Boolean> verifyVerificationCode(String email, String code) {String storedCode = verificationCodes.get(email);if (storedCode != null && storedCode.equals(code)) {verificationCodes.remove(email);return Result.success(true);}return Result.success(false);}private String generateVerificationCode() {Random random = new Random();StringBuilder code = new StringBuilder();for (int i = 0; i < 6; i++) {code.append(random.nextInt(10));}return code.toString();}
}
  • sendVerificationCode 方法:

    • 生成一个 6 位的随机验证码。
    • 将验证码存储在 verificationCodes 映射中,键为用户邮箱。
    • 创建一个 SimpleMailMessage 对象,设置发件人、收件人、主题和正文。
    • 使用 JavaMailSender 发送邮件。
    • 根据发送结果返回成功或失败的 Result 对象。
  • verifyVerificationCode 方法:

    • 从 verificationCodes 映射中获取存储的验证码。
    • 比较用户输入的验证码和存储的验证码,如果匹配则返回 true,否则返回 false

4. 控制器

EmailController 类提供了发送和验证验证码的 RESTful 接口:

package com.example.house.Controller;import com.example.house.Service.EmailService;
import com.example.house.Utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/email")
public class EmailController {@Autowiredprivate EmailService emailService;@PostMapping("/sendCode")public Result<String> sendVerificationCode(@RequestParam String email) {System.out.println("Received email: " + email);return emailService.sendVerificationCode(email);}@PostMapping("/verifyCode")public Result<Boolean> verifyVerificationCode(@RequestParam String email, @RequestParam String code) {return emailService.verifyVerificationCode(email, code);}
}
  • /email/sendCode 接口:接收用户邮箱作为参数,调用 EmailService 的 sendVerificationCode 方法发送验证码邮件。
  • /email/verifyCode 接口:接收用户邮箱和验证码作为参数,调用 EmailService 的 verifyVerificationCode 方法验证验证码。
http://www.xdnf.cn/news/617617.html

相关文章:

  • 重读《人件》Peopleware -(12-1)Ⅱ 办公环境 Ⅴ 大脑时间与身体时间(上)
  • 超简单 FishSpeech 本地部署
  • 【游戏设计】游戏玩法与游戏机制
  • 决策树引导:如何选择最适合你的机器学习算法
  • 文章记单词 | 第110篇(六级)
  • Java 8 Lambda 表达式使用说明与案例
  • 前端测试简介
  • Python排序函数全面指南:从基础到高级
  • 字符编码详解:ASCII、Latin1、Unicode、UTF-8 与 GBK
  • 365打卡第N1周: one-hot编码案例
  • 【数据反哺运营】用Python构建可落地的商品结构分析方法论-某朴超市
  • 【风控】申请评分卡(A卡)模型
  • QString 写时拷贝简介
  • 2025年电工杯B题思路讲解问题一四种算法
  • Java 集合框架核心知识点全解析:从入门到高频面试题(含 JDK 源码剖析)
  • 解决:dpkg: error: dpkg frontend lock is locked by another process
  • Coze工作流-变量聚合模块的应用
  • IEEE 流程
  • OSS对象存储如何避免被攻击恶意刷流量?
  • QT中延时的用法及定时器的用法
  • 异地容灾、热备与冷备:核心概念解析、技术对比及行业解决方案指南
  • 在Android APK中使用WebView加载Vue项目并实现文件导出
  • 电网绝缘子及破损、闪络缺陷YOLO数据集
  • 【工具变量】地级市创新重视程度数据及城市创新重视程度数据(2003-2025年)
  • 旅游信息检索
  • 每日算法-250523
  • 1.2.1+1.2.2计算机硬件的基本组成
  • 通信专业速成solidworks学习记录
  • 有限时间 vs 固定时间 vs 预定时间滑模:稳定性分析与仿真验证方法对比(上)
  • 本地分支git push 报错 fatal: The current branch XXXX has no upstream branch.