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
方法验证验证码。