网易云邮箱验证码注册及修改密码

网易云邮箱发送验证码

1、进入网易云邮箱官网,点击设置进入POP3/SMTP/IMAP

在这里插入图片描述

2、开启服务

在这里插入图片描述

3、新增授权密码,并保存

在这里插入图片描述

4、pom.xml文件添加依赖

<!--thymeleaf-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

5、添加application-mail.yml配置文件

spring:
  mail:
    host: smtp.163.com      # SMTP服务器地址
    username: xxxx@163.com # 发件人的邮箱
    password: xxxxxxxxx # 授权密码
    properties.mail.smtp.port: 465 # 465 or 994
    nickname: 志小志    #发件人名称
    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true
    default-encoding: utf-8

6、Controller层代码,前端传入收件人的邮箱

package com.qiu.controller;

import com.aliyuncs.utils.StringUtils;
import com.qiu.util.general.CommonResult;
import com.qiu.util.general.MyUtils;
//import com.qiu.util.mail.IMailService;
import com.qiu.util.mail.IMailService;
import com.qiu.util.sms.AliYunSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Captain
 * @email qiudb.top@aliyun.com
 * @date 2020/10/29 15:11
 * @description 发送邮件、产生验证码图片、发送短信等工具类操作
 */
@CrossOrigin
@RestController
public class UtilController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

//    @Autowired
//    private AliYunSmsService aliYunSmsService;

    @Autowired
    private IMailService mailService;

    /**
     * 发送邮箱随机验证码
     * @param email 邮箱地址
     */
    @RequestMapping(value = "/allow/sendHtmlCode")
    public CommonResult sendHtmlCode(String email) {
        try {
            //工具类,随机生成六位数验证码
            String code = MyUtils.getCode(6);
            Map<String, Object> data = new HashMap<>(2);
            data.put("code", code);
            data.put("year", Calendar.getInstance().get(Calendar.YEAR));
            redisTemplate.opsForValue().set(email, code, 10, TimeUnit.MINUTES);
            mailService.sendTemplateMail(email, "操作验证码", "mail", data);
            return CommonResult.success("验证码已发送,网络有延迟请稍等~");
        } catch (Exception e) {
            return CommonResult.error("发送验证码时发生异常,请稍后重试!");
        }
    }

    /**
     * 发送注册成功邮箱
     *
     * @param email    邮箱地址
     * @param name     用户名
     * @param password 密码
     */
    @RequestMapping(value = "/allow/sendHtmlRegister")
    public CommonResult sendRegisterInfo(String email, String name, String password) {
        try {
            Map<String, Object> data = new HashMap<>(4);
            data.put("account", email);
            data.put("name", name);
            data.put("password", password);
            data.put("year", Calendar.getInstance().get(Calendar.YEAR));
            mailService.sendTemplateMail(email, "注册成功", "register", data);
            return CommonResult.success("注册信息发送成功");
        } catch (Exception e) {
            return CommonResult.error("注册信息发送失败");
        }
    }

    /**
     * 发送角色更新邮件
     *
     * @param email    邮箱地址
     * @param userName 用户名
     * @param roleInfo 角色信息
     */
    @RequestMapping(value = "/allow/sendHtmlRole")
    public CommonResult sendRoleInfo(String email, String userName, String roleInfo) {
        try {
            Map<String, Object> data = new HashMap<>(3);
            data.put("userName", userName);
            data.put("roleInfo", roleInfo);
            data.put("year", Calendar.getInstance().get(Calendar.YEAR));
            mailService.sendTemplateMail(email, "权限管理", "role", data);
            return CommonResult.success("授权信息发送成功");
        } catch (Exception e) {
            return CommonResult.error("授权信息发送失败");
        }
    }

    /**
     * 重置密码
     *
     * @param email    邮箱地址
     * @param password 密码
     */
    @RequestMapping(value = "/allow/sendHtmlResetPwd")
    public CommonResult sendResetPwd(String email, String password) {
        try {
            Map<String, Object> data = new HashMap<>(2);
            data.put("password", password);
            data.put("year", Calendar.getInstance().get(Calendar.YEAR));
            mailService.sendTemplateMail(email, "重置密码", "resetpwd", data);
            return CommonResult.success("新密码信息发送成功");
        } catch (Exception e) {
            return CommonResult.error("新密码信息发送失败");
        }
    }


    /**
     * 验证输入的验证码是否正确
     *
     * @param key  验证的依据
     * @param code 验证码
     */
    @RequestMapping(value = "/allow/checkCode")
    public CommonResult checkCode(String key, String code) {
        String codeK = redisTemplate.opsForValue().get(key);
        if (codeK == null) {
            return CommonResult.error("验证码不存在或已过期,请重新发送!");
        }
        if (codeK.equals(code)) {
            redisTemplate.delete(key);
            return CommonResult.success("验证码成功!", true);
        } else {
            return CommonResult.success("验证码错误!", false);
        }
    }

    /**
     * 用于绑定手机号操作,发送验证码
     *
     * @param phone 发送的手机号
     */
//    @RequestMapping(value = "/util/smsCode")
//    public CommonResult aliYunSmsCode(String phone) {
//        if (!StringUtils.isEmpty(redisTemplate.opsForValue().get(phone))) {
//            return CommonResult.error(phone + "的验证码还未过期!");
//        }
//        //生成验证码并存储到redis中
//        String code = MyUtils.getCode(6);
//        if (aliYunSmsService.sendSms(phone, code)) {
//            redisTemplate.opsForValue().set(phone, code, 10, TimeUnit.MINUTES);
//            return CommonResult.success("验证码已发送,网络有延迟请稍等~");
//        } else {
//            return CommonResult.error("验证码发送失败,请稍后重试~");
//        }
//    }
}
//自定义工具类,生成验证码
public class MyUtils {
    public static String getCode(int length) {
        String str = String.valueOf(System.currentTimeMillis());
        return str.substring(str.length() - length);
    }
    private MyUtils() {
    }
}

7、service层

package com.qiu.util.mail;

import java.util.Map;

/**
 * @author Captain
 * 发送邮箱
 */
public interface IMailService {
    /**
     * 发送文本邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    void sendSimpleMail(String to, String subject, String content);

    /**
     * 发送HTML邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     * @throws Exception 异常信息
     */
    void sendHtmlMail(String to, String subject, String content) throws Exception;

    /**
     * 发送带附件的邮件
     *
     * @param to       收件人
     * @param subject  主题
     * @param content  内容
     * @param filePath 附件
     * @throws Exception 异常信息
     */
    void sendAttachmentsMail(String to, String subject, String content, String filePath) throws Exception;


    /**
     * 发送模板邮件
     *
     * @param to       收件人
     * @param subject  主题
     * @param template 邮件模板
     * @param data     模板参数
     * @throws Exception 异常信息
     */
    void sendTemplateMail(String to, String subject, String template, Map<String, Object> data) throws Exception;
}

8、service层的实现类impl

package com.qiu.util.mail.impl;

import com.qiu.util.mail.IMailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Map;

/**
 * @author Captain
 */
@Slf4j
@Async
@Service
public class IMailServiceImpl implements IMailService {

    @Autowired
    private TemplateEngine templateEngine;

    @Resource
    private JavaMailSender mailSender;

    /**
     * 邮件昵称
     */
    @Value("${spring.mail.nickname}")
    private String nickname;

    /**
     * 发送的邮箱地址
     */
    @Value("${spring.mail.username}")
    private String from;


    /**
     * 简单文本邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        //创建SimpleMailMessage对象
        SimpleMailMessage message = new SimpleMailMessage();
        //邮件发送人
        message.setFrom(nickname + '<' + from + '>');
        //邮件接收人
        message.setTo(to);
        //邮件主题
        message.setSubject(subject);
        //邮件内容
        message.setText(content);
        //发送邮件
        mailSender.send(message);
        log.info("邮件已经发送");
    }

    /**
     * html邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) throws Exception {
        //获取MimeMessage对象
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        messageHelper = new MimeMessageHelper(message, true);
        //邮件发送人
        message.setFrom(nickname + '<' + from + '>');
        //邮件接收人
        messageHelper.setTo(to);
        //邮件主题
        message.setSubject(subject);
        //邮件内容,html格式
        messageHelper.setText(content, true);
        mailSender.send(message);
        log.info("邮件已经发送");
    }

    /**
     * 带附件的邮件
     *
     * @param to       收件人
     * @param subject  主题
     * @param content  内容
     * @param filePath 附件
     */
    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) throws Exception {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(nickname + '<' + from + '>');
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        FileSystemResource file = new FileSystemResource(new File(filePath));
        String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
        helper.addAttachment(fileName, file);
        log.info("邮件已经发送");
    }


    /**
     * 发送模板邮件 使用thymeleaf模板
     *
     * @param to      收件人
     * @param subject 主题
     * @param data    模板内容
     */
    @Async
    @Override
    public void sendTemplateMail(String to, String subject, String template, Map<String, Object> data) throws Exception {
        System.out.println("to="+to);
        System.out.println("subject="+subject);
        System.out.println("template="+template);
        System.out.println("data="+data);
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
        // 发送人的邮箱
        messageHelper.setFrom(nickname + '<' + from + '>');
        // 发给谁,对方邮箱
        messageHelper.setTo(to);
        // 邮件标题
        messageHelper.setSubject(subject);
        Context context = new Context();
        //定义模板数据
        context.setVariables(data);
        //获取thymeleaf的html模板
        String emailContent = templateEngine.process(template, context); //指定模板路径
        messageHelper.setText(emailContent, true);
        mailSender.send(mimeMessage);
        log.info("邮件已经发送");
    }
}

9、mail.html 邮箱验证码模板

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="format-detection" content="telephone=no"/>
    <title>乐购商城</title>
</head>
<body style="font-size: 13px">
<div class="main" style="padding-bottom:40px;background-color:#F1F1F1;">
    <div class="header" style="padding: 10px 3%">
        <h2 style="text-align:center;color: #FF6633">
                乐购商城
        </h2>
    </div>

    <div class="content" style="overflow: hidden;padding:15px 5% 70px 5%;margin:0 2%;background-color: #fff;box-shadow:0 4px 20px rgba(0,0,0,0.1);word-break: break-all;">
        <p style="font-weight: bolder;margin-bottom: 5px;">尊敬的乐购商城用户,您好:</p>
        <p style="margin-bottom: 30px;text-indent: 2em">请使用下面的验证码验证您的操作,验证码 10 分钟内有效: <a href="javascirpt:void(0)" onclick="return false;" th:text="${code}">602510</a></p>
    </div>
</div>
<div class="footer" style="padding:7px 20px;background-color:#333;font-size:12px;color: #999;text-align: center">
    <p content="telephone=no">Copyright&nbsp;©&nbsp;2020&nbsp;-&nbsp;<span th:text="${year}">2020</span>
</div>
</body>
</html>

10、resetpwd.html 重置密码模板

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="format-detection" content="telephone=no"/>
    <title>乐购商城</title>
    <style>
        #cover{
            border-radius: 6px;
            outline:none;
            height: 25px;
            width: 122px;
            cursor: pointer;
            border:none;
            background-color:#00DFDF;
        }
    </style>
    <script>
        function buttonClick(){
            let password = document.getElementById("password");
            let cover = document.getElementById("cover");
            if(cover.innerText==='点击即可显示密码'){
                cover.innerText='隐藏密码'
                password.style.display='inline'
            }else{
                cover.innerText='点击即可显示密码'
                password.style.display='none'
            }
        }
    </script>
</head>
<body style="font-size: 13px">
<div class="main" style="padding-bottom:40px;background-color:#F1F1F1;">
    <div class="header" style="padding: 10px 3%">
        <h2 style="text-align:center;color: #FF6633">
                乐购商城
        </h2>
    </div>
    <div class="content" style="overflow: hidden;padding:15px 5% 70px 5%;margin:0 2%;background-color: #fff;box-shadow:0 4px 20px rgba(0,0,0,0.1);word-break: break-all;">
        <p style="font-weight: bolder;margin-bottom: 5px;">尊敬的乐购商城用户,您好:</p>
        <span style="text-indent: 2em;padding-left: 2em">密码重置成功,新密码为</span>
        <p style="display: inline">
            <span id="password" style="padding: 0 8px;font-weight: bolder; font-size: 15px;" th:text="${password}">123456</span>
<!--            <button id="cover" οnclick="buttonClick()">点击即可显示密码</button>-->
        </p>
    </div>
</div>
<div class="footer" style="padding:7px 20px;background-color:#333;font-size:12px;color: #999;text-align: center">
    <p content="telephone=no">Copyright&nbsp;©&nbsp;2020&nbsp;-&nbsp;<span th:text="${year}">2020</span>
</div>
</body>
</html>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值