在開發用戶系統時,發送郵件是一項常見需求,例如用戶忘記密碼時,通過郵箱發送驗證碼來驗證身份并重置密碼。本文將結合 Spring Boot 和 163 郵箱,演示如何實現郵件發送功能。
一、前提條件
普通用戶的 163 郵箱可以在 Spring Boot 項目中用于發送郵件,但需要完成以下配置:
1. 登錄 163 郵箱
使用普通賬號登錄 163 郵箱官網。
2. 開啟 SMTP 服務
- 點擊郵箱右上角「設置」→「POP3/SMTP/IMAP」;
- 在 SMTP 服務選項中勾選「開啟 SMTP 服務」;
- 按提示完成手機驗證(163 郵箱要求綁定手機號才能開啟該服務)。
3. 獲取授權碼
- 開啟 SMTP 后,頁面會提示生成授權碼;
- 按照提示生成 16 位授權碼(例如
abcdefghijklmnop
),保存好; - 該授權碼將在 Spring Boot 郵件配置中替代郵箱密碼。
?? 注意:普通 163 郵箱每天發送量有限,適合開發和測試用途。
二、Spring Boot 郵件依賴
在 pom.xml
中添加 Spring Boot 郵件依賴:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId>
</dependency>
三、Spring Boot 郵件配置
在 application.yml
或 application.properties
中添加 163 郵箱 SMTP 配置:
spring:
# 配置郵箱服務器,賬號密碼等mail:host: smtp.163.comusername: 1888888888@163.compassword: agagtfgsdhdcode:overtime: 5
其中
password
是生成的授權碼,而非郵箱密碼。
四、郵件發送服務實現
創建 MailService
接口:
public interface MailService {Result<String> getCode(String username, String mailAddress);
}
創建 MailServiceImpl
實現類:
@Service
public class MailServiceImpl implements MailService {@Autowiredprivate JavaMailSender mailSender;@Autowiredprivate StringRedisTemplate redisTemplate;@Autowiredprivate UserMapper userMapper;@Value("${spring.mail.username}")private String mailUserName;@Value("${spring.mail.code.overtime}")private Integer overtime; // 驗證碼過期時間(分鐘)@Overridepublic Result<String> getCode(String username, String mailAddress) {// 校驗用戶名和郵箱if (StringUtils.isBlank(username)) return Result.fail("賬號不能為空!");if (StringUtils.isBlank(mailAddress)) return Result.fail("郵箱不能為空!");User user = userMapper.selectUserByUsername(username);if (user == null) return Result.fail("賬號不存在!");if (!user.getEmail().equals(mailAddress)) return Result.fail("輸入郵箱和預留郵箱不一致!");// 生成驗證碼String verifyCode = redisTemplate.opsForValue().get("MAIL_CODE_" + username);if (verifyCode == null) {verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);}redisTemplate.opsForValue().set("MAIL_CODE_" + username, verifyCode, overtime, TimeUnit.MINUTES);// 構建郵件內容String content = "<html><body>"+ "您好<br/>"+ "您的驗證碼是:" + verifyCode + "<br/>"+ "在" + overtime + "分鐘內有效,請盡快使用。<br/>"+ "若非本人操作,請忽略此郵件。"+ "</body></html>";try {MimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setFrom(mailUserName);helper.setTo(mailAddress);helper.setSubject("找回密碼驗證碼");helper.setText(content, true);mailSender.send(message);} catch (MessagingException e) {e.printStackTrace();return Result.fail("郵件發送失敗!");}return Result.ok("驗證碼已發送至郵箱:" + mailAddress);}
}
五、郵件控制器
@RestController
@RequestMapping("/mail")
public class MailController {@Autowiredprivate MailService mailService;@GetMapping("/getCode")@ApiOperation("獲取重置密碼驗證碼")public Result<String> getCode(String username, String mailAddress){return mailService.getCode(username, mailAddress);}
}
六、Redis 驗證碼存儲
-
使用
StringRedisTemplate
存儲驗證碼:- Key:
MAIL_CODE_用戶名
- Value: 驗證碼
- TTL:
spring.mail.code.overtime
分鐘
- Key:
-
發送郵件后驗證碼會被存入 Redis,用戶提交時進行比對。