Springboot realizes the function of sending email verification code in applet

For more details, please visit my blog: Springboot implements the function of sending email verification code in the applet

Springboot implements email verification for applets

1. Configuration items

  1. Configure pom files and introduce dependency on sending emails

Add in the pom file:

<!--邮件发送核心包-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

  1. Modify the configuration file application.yml, here take the QQ mailbox as an example

I use the yml method here, of course, you can also use the properties method to write

#邮件发送配置
spring:
  mail:
    default-encoding: UTF-8
    host: smtp.qq.com
    username: 你的邮箱
    password: 邮箱授权码
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true

The email authorization code can be obtained as follows:

Open the QQ mailbox page → Settings → Account → POP3 / IMAP / SMTP / Exchange / CardDAV / CalDAV service → turn on the POP3 / SMTP service, and then you can see the authorization code

[External chain image transfer failed. The source site may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-k05s3Fon-1578461968057) )]

Second, write mailService and mailServiceImpl

The mail service layer and the mail service interface implementation layer

$ {spring.mail.username} is a property configured in yml. There is a method here. The first is to send regular mail, and the second is to send mail with attachments.

  1. Mail Service Layer (IMailService)
public interface IMailService {

    //发送普通邮件
    void sendSimpleMail(String to,String title,String content);

    //发送带有附件的邮件
    void sendAttachmentsMail(String to, String title, String content, List<File> fileList);
}
  1. Mail service interface implementation layer (MailServiceImpl)
@Service
public class MailServiceImpl implements IMailService {

    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private JavaMailSender mailSender;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    //发送普通邮件
    @Override
    public void sendSimpleMail(String to, String title, String content) {

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(title);
        message.setText(content);
        mailSender.send(message);
        logger.info("邮件发送成功");

    }

    //发送带有附件的邮件
    @Override
    public void sendAttachmentsMail(String to, String title, String content, List<File> fileList) {

        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(title);
            helper.setText(content);
            String fileName = null;
            for (File file:fileList) {
                fileName = MimeUtility.encodeText(file.getName(), "GB2312", "B");
                helper.addAttachment(fileName, file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mailSender.send(message);
        logger.info("邮件发送成功");

    }
}

Third, write the controller

E-mail control layer

//获取邮箱验证的验证码
    @RequestMapping("/getCheckCode")
    public JsonResult getCheckCode(HttpServletRequest request) {
        //获取微信小程序get的参数值并打印
        String userEmail = request.getParameter("userEmail");
        user = userService.queryUserByUserEmail(userEmail);
        if (null == user) {
            return new JsonResult(JsonResponseStatus.EMPTY.getCode(), JsonResponseStatus.EMPTY.getMsg());
        }else{
            String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
            String message = "您的注册验证码为:"+checkCode;
            try {
                mailService.sendSimpleMail(userEmail, "注册验证码", message);
            }catch (Exception e){
                return new JsonResult(JsonResponseStatus.EMPTY.getCode(), JsonResponseStatus.EMPTY.getMsg());
            }
            return new JsonResult(JsonResponseStatus.SUCCESS.getCode(), JsonResponseStatus.SUCCESS.getMsg(),checkCode);
        }
    }

Attach the control layer code that can be used on the Web page:

@Controller
public class MailController {
    
    @Resource
    private IMailService mailService;

    @RequestMapping("getCheckCode")
    @ResponseBody
    public String getCheckCode(String email){
        String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
        String message = "您的注册验证码为:"+checkCode;
        try {
            mailService.sendSimpleMail(email, "注册验证码", message);
        }catch (Exception e){
            return "";
        }
        return checkCode;
    }
}

Fourth, write a small program email verification page

<!--pages/getCheckCode/getCheckCode.wxml-->
<form bindsubmit="getCheckCode">
  <view class="form-list">
    <view class="form-item">
      <view class="form-item-hd">邮箱</view>
      <view class="form-item-bd">
        <input type="email" name="userEmail" value="{{userEmail}}" placeholder="请输入邮箱" maxlength="25" />
      </view>
    </view>
  </view>
  <!--按钮-->
  <button formType="submit" class="edit-btn">获取验证码</button>
</form>

<form bindsubmit="toPasswordReset">
  <view class="form-list">
    <view class="form-item">
      <view class="form-item-hd">验证码</view>
      <view class="form-item-bd">
        <input type="text" name="checkCode" value="{{checkCode}}" placeholder="请输入验证码" maxlength="20" />
      </view>
    </view>
  </view>
  <button formType="submit" class="edit-btn">进行验证</button>
</form>

Five, test

[External chain image transfer failed, the source site may have an anti-theft chain mechanism, it is recommended to save the image and upload it directly (img-0JFwnvF6-1578461968058) (https://i.loli.net/2019/03/16/5c8cc99015151.png )]

[External chain image transfer failed, the source site may have an anti-theft chain mechanism, it is recommended to save the image and upload it directly (img-jFDlrDTs-1578461968059) (https://i.loli.net/2019/03/16/5c8cc9a7008c2.png )]

Ok, I ’ll share it here. If you have any questions, please leave a comment below ...

Published 120 original articles · praised 201 · 230,000 views +

Guess you like

Origin blog.csdn.net/wugenqiang/article/details/88604632