【邮箱验证码】springboot 使用邮箱服务发送验证码 ,在阿里云服务器端口的配置

1、我们需要登录邮箱开通邮箱授权码

在这里插入图片描述

2、然后需要pom需要引入spring-boot-starter-mail

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
        <version>2.6.4</version>
    </dependency>

需要在配置文件 application.properties里面添加

<!-- 邮箱验证 -->
#163邮箱
spring.mail.host=smtp.163.com
#这里配置你的邮箱
spring.mail.username=XXX@163.com
spring.mail.password=开启smtp时候的授权码
spring.mail.default-encoding=utf-8
spring.mail.port=465
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory

如果这里指定465端口,该端口和项目服务端口不冲突。邮件发送协议必须是smtps 不指定发送邮件时会报错,所以必须指定protocol配置为smtps

逻辑代码

上边pom的spring-boot-starter-mail引入后你能使用

JavaMailSender 是mail包提供的

package com.qiyuan.qyframe.base.service;

import com.qiyuan.qyframe.base.common.BusiException;
import com.qiyuan.qyframe.base.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

@Slf4j
@Service
public class EmailService {

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

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JavaMailSender sender;

   
    public void sendEmailCode(String email) {
        if (StringUtils.isBlank(email)) {
            throw new BusiException("请输入正确的邮箱账号");
        }
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(username);
        message.setTo(email);
        message.setSubject("验证码");
        String verificationCode = String.valueOf(new Random().nextInt(899999) + 100000);
        //System.out.println(verificationCode);
        message.setText("尊敬的用户你好,你所收到的验证码: " + verificationCode);

        sender.send(message);
        //将验证码放入Redis中,并定时五分钟,五分钟后删除
        redisUtil.set(email, verificationCode, 5 * 60);

    }
}

然后你就可以在你的业务代码中调上边封装的EmailService了

	@AnonymousAccess
    @RequestMapping(value = "/emailCode", method = RequestMethod.POST)
    public ResponseData emailCode(String email) {
        String errMsg = "";
        try {
            emailService.sendEmailCode(email);

        } catch (BusiException e) {
            errMsg = e.getMessage();
            log.error("PhoneCodeController-emailCode occur BusiException", e);
            return ResponseDataUtil.buildSuccess(ResultEnums.ERROR.getCode(), errMsg);
        } catch (Exception e) {
            //异常信息
            errMsg = "系统错误";
            log.error("PhoneCodeController-emailCode occur Exception", e);
            return ResponseDataUtil.buildSuccess(ResultEnums.ERROR.getCode(), errMsg);
        }
        return ResponseDataUtil.buildSuccess(ResultEnums.SUCCESS.getCode(), "操作成功");

    }

流程大概就这些啦,应该没啥问题了,搞定

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
阿里云短信验证码的Java代码示例如下: ``` import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import com.aliyuncs.sms.model.v20160927.SendSmsRequest; import com.aliyuncs.sms.model.v20160927.SendSmsResponse; public class AliyunSmsUtil { public static void sendSms(String phoneNumbers, String signName, String templateCode, String templateParam) { // 设置超时时间-可自行调整 System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); System.setProperty("sun.net.client.defaultReadTimeout", "10000"); // 初始化ascClient需要的几个参数 final String product = "Dysmsapi"; final String domain = "dysmsapi.aliyuncs.com"; // 替换成你的AK (产品密) final String accessKeyId = "yourAccessKeyId";// 你的accessKeyId,参考本文档步骤2 final String accessKeySecret = "yourAccessKeySecret";// 你的accessKeySecret,参考本文档步骤2 // 初始化ascClient,暂时不支持多region(请勿修改) IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret); try { DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); } catch (ClientException e) { e.printStackTrace(); } IAcsClient acsClient = new DefaultAcsClient(profile); // 组装请求对象 SendSmsRequest request = new SendSmsRequest(); // 必填:待发送手机号 request.setPhoneNumbers(phoneNumbers); // 必填:短信签名-可在短信控制台中找到 request.setSignName(signName); // 必填:短信模板-可在短信控制台中找到 request.setTemplateCode(templateCode); // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 request.setTemplateParam(templateParam); // 发送请求 try { SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request); if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) { // 请求成功 System.out.println("短信发送成功!"); } else { System.out.println("短信发送失败:" + sendSmsResponse.getMessage()); } } catch (ServerException e) { e.printStackTrace(); } catch (ClientException e) { e.printStackTrace(); } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值