欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

SpringBoot发送验证码

时间:2023-06-08

1创建Spring Boot项目

2导入依赖

org.springframework.boot spring-boot-starter-mail 2.6.3

3配置application.yml

spring: mail: host: # 邮箱服务器 例:smtp.qq.com username: ****@qq.com password: **** properties: mail: smtp: auth: true starttls: enable: true required: true

4MailService.java

package com.zhangz1.maildemo.service;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;import org.springframework.stereotype.Service;import javax.annotation.Resource;import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;@Servicepublic class MailService { @Resource JavaMailSender mailSender; private final Logger logger = LoggerFactory.getLogger(MailService.class); public String send(String sender, String receiver, String title, String text) { try { //建立邮件消息 MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); //发送方 helper.setFrom(sender); //接收方 helper.setTo(receiver); //发送的标题 helper.setSubject(title); //发送的内容 helper.setText(text); mailSender.send(message); } catch (MessagingException e) { logger.error(e.getMessage()); } return "发送成功"; }}

5MailController.java

package com.zhangz1.maildemo.controller;import com.zhangz1.maildemo.service.MailService;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;import java.util.Random;@RestControllerpublic class MailController { @Resource private MailService mailService; @RequestMapping("/sendMail") public String send() { String checkCode = String.valueOf(new Random().nextInt(899999) + 100000); String sender = "2659445660@qq.com"; //发送方邮箱 String receiver = "admin@zhangz1.top"; //接收方邮箱 String title = "验证码"; String text = "您的验证码为" + checkCode; return mailService.send(sender, receiver, title, text); }}

6测试


Spring框架中Java邮件支持的接口和类组织如下:

MailSender接口:提供发送简单电子邮件的基本功能的顶级接口JavaMailSender接口:上述MailSender的子接口。它支持 MIME 消息,并且主要与MimeMessageHelper类一起用于创建MimeMessage。建议将此接口使用MimeMessagePreparator机制。JavaMailSenderImpl类:提供了JavaMailSender接口的实现。它支持MimeMessageSimpleMailMessage。SimpleMailMessage类:用于创建简单的邮件消息,包括 from、to、cc、subject 和 text 字段MimeMessagePreparator接口:提供了一个回调接口,用于准备 MIME 消息。MimeMessageHelper类:用于创建 MIME 消息的帮助类。它支持 HTML 布局中的图像、典型邮件附件和文本内容。

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。