java集成短信服务 测试版 qq邮箱简单思路

java集成短信服务

注册一个帐号

使用的是容联云,百度搜一下官网

用手机注册一个帐号就行,免费体验不需要认证
注册后会有八块钱送,可以使用免费的给自己设置三个固定手机号发送短信,不需要认证。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-T2UjPY6t-1690897179638)(E:\personboke\blog\source_posts\java集成短信服务\image-20230801213129678.png)]

此页面的 三个信息需要在代码中去进行填写认证

主账户

账户授权令牌

访问的Rest URl

APP id

绑定用于接收短信的手机号

控制台—管理—号码管理—测试号码"绑定 测试号码

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-T2UjPY6t-1690897179638)(E:\personboke\blog\source_posts\java集成短信服务\image-20230801213129678.png)]

添加maven依赖

jdk要使用8以上

<dependency>
    <groupId>com.cloopen</groupId>
    <artifactId>java-sms-sdk</artifactId>
    <version>1.0.3</version>
</dependency>

测试代码

我们需要把以上四个信息填入,还有接收短信的手机号码验证码需要自己手动生成,(这里使用四位随机整数),然后将这些信息传到短信服务平台帮我们发送。

@Component
public class SendMessage {
        public static String message(String phone){
            //返回产生的验证码
            String code= null;
            //生产环境请求地址:app.cloopen.com
            String serverIp = "app.cloopen.com";
            //请求端口
            String serverPort = "8883";
            //主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
            String accountSId ="自己的";
            String accountToken = "自己的";
            //请使用管理控制台中已创建应用的APPID
            String appId = "自己的";
            CCPRestSmsSDK sdk = new CCPRestSmsSDK();
            sdk.init(serverIp, serverPort);
            sdk.setAccount(accountSId, accountToken);
            sdk.setAppId(appId);
            sdk.setBodyType(BodyType.Type_JSON);
            //手机号码
            String to = phone;
            String templateId= "1";//使用的模板id
            //生成四位随机数
            int random=(int)(Math.random()*10000);
            code = String.valueOf(random);
            String[] datas = {code,"2"};//格式:你的验证码是{code},请于{2}分钟内正确输入
            //HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas);
            HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas);
            if("000000".equals(result.get("statusCode"))){
                //正常返回输出data包体信息(map)
                HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
                Set<String> keySet = data.keySet();
                for(String key:keySet){
                    Object object = data.get(key);
                    System.out.println(key +" = "+object);
                }
            }else{
                //异常返回输出错误码和错误信息
                System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
            }
            return code;
        }
}

调用方法一并附上防止有看不懂的

package com.atheima.reggie.controller;

import com.atheima.reggie.Utils.SendMessageUtils;
import com.atheima.reggie.Utils.ValidateCodeUtils;
import com.atheima.reggie.common.R;
import com.atheima.reggie.common.SendMessage;
import com.atheima.reggie.entity.User;
import com.atheima.reggie.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SendMessage sendMessage;
    @PostMapping("/sendMsg")
    public R<String> sendMessage(@RequestBody User user, HttpSession session){
        String phone=user.getPhone();
        //获取手机号
//        if (StringUtils.isNotEmpty(phone)){
//            //生成随机的四位验证码
//            Integer integer = ValidateCodeUtils.generateValidateCode(4);
//            String code = integer.toString();
            SendMessageUtils.message(phone);
//            //调用api短信
//            //需要生成的验证码保存到session
            session.setAttribute(phone,code);
//            //将生成的验证码缓存到redis中并且设置有效期5分钟
//            redisTemplate.opsForValue().set(phone,code,5,TimeUnit.MINUTES);
//            log.info("Sent message"+code);
//        SendMessage()
        String code=sendMessage.message(phone);
        if (StringUtils.isNotEmpty(code)){
            session.setAttribute(phone,code);
          //将生成的验证码缓存到redis中并且设置有效期5分钟
            redisTemplate.opsForValue().set(phone,code,5,TimeUnit.MINUTES);
            log.info("Sent message"+code);
            return R.success("验证码登录成功");
        }
        return R.success("验证码登录失败");
        }
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        log.info(map.toString());
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //从cookie中
//        String phonecodeinsessoin =(String) session.getAttribute(phone);
        //从Redis中获取缓存验证码
        String phonecodeinsessoin=(String) redisTemplate.opsForValue().get(phone);
        if (phonecodeinsessoin!=null&&phonecodeinsessoin.equals(code)){
            LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(lambdaQueryWrapper);
            if (user==null){
                user=new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            //如果用户登陆成功则删除缓存验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登陆失败");
    }
    @PostMapping("/loginout")
    public R<String> loginout(@RequestBody Map map,HttpSession session){
        session.removeAttribute("user");
        return R.success("退出成功");
    }
}

示例

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-29o1C7li-1690897334327)(E:\personboke\blog\source_posts\java集成短信服务\image-20230801213715539.png)]

Springboot集成qq邮箱

自己以前做过就不多赘述
以下文章来自博客
https://blog.csdn.net/sdrfghb/article/details/126845550?
提示:以下是本篇文章正文内容,下面案例可供参考

邮箱设置
这边主要展示qq邮箱设置,网易或别的邮箱请自行百度设置

qq邮箱地址
打开账号POP3/SMTP服务

注意保存授权码

添加依赖,为了让验证码页面好看点,咱们可以使用thymeleaf

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

yaml 配置
spring:
mail:
# 邮箱服务器地址
host: smtp.qq.com
# 账号
username: qq号
# 密码
password: 上面qq邮箱的授权码
# 编码格式
default-encoding: UTF-8
# 超时时间
properties:
mail:
smtp:
auth: true
enable: true
connectiontimeout: 10000
timeout: 10000
writetimeout: 10000
# 配置SSL 加密工厂
socketFactoryClass: javax.net.ssl.SSLSocketFactory
# 表示开启 DEBUG 模式,这样,邮件发送过程的日志会在控制台打印出来,方便排查错误
debug: true

封装工具类
/**
* description: 使用thymeleaf模板发送邮件
*
* @param subject 主题
* @param map Thymeleaf html模板参数
* @param htmlName 模板名称
* @param addressee 收件人
* @return boolean
* @author Tigger
*/
public boolean sendThymeleafMail(String subject, Map<String, Object> map, String htmlName, String… addressee) {
boolean flag = false;
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = null;
mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
// 邮件发送者
mimeMessageHelper.setFrom(from);
// 邮件接受者
mimeMessageHelper.setTo(addressee);
// 主题
mimeMessageHelper.setSubject(subject);

        // 这里引入的是Template的Context
        Context context = new Context();
        // 设置模板中的变量
        context.setVariables(map);
        // 第一个参数为模板的名称
        String process = templateEngine.process(htmlName, context);
        // 第二个参数true表示这是一个html文本
        mimeMessageHelper.setText(process,true);
        javaMailSender.send(mimeMessage);
        flag = true;
    }
    catch (MessagingException e) {
        e.printStackTrace();
    }
    return flag;
}

使用,这边使用了lombok和redis,需要的自己引下依赖,不需要的自行删除。
/**

  • description: 生成指定位数短信验证码
  • @param count 指定位数
  • @return java.lang.String
  • @author Tigger
    */
    private String getRandCode(int count) {
    return String.valueOf((int)((Math.random()9+1) Math.pow(10,count-1)));
    }

/**

  • description: 发送邮箱验证码
  • @param mailNumber 发送邮箱账号
  • @return java.lang.String
  • @author Tigger
    */
    public String sendCodeMailInfo(String mailNumber) {
    String sendMessage = null;
    String randCode = getRandCode(6);
    log.info(“邮箱验证码-{}”, randCode);
    Map<String, Object> stringObjectMap = new HashMap<>(1);
    stringObjectMap.put(“codeMessage”, randCode);
    boolean mail = mailUtil.sendThymeleafMail(“验证码”, stringObjectMap, “mailAssign.html”, mailNumber);
    if (mail) {
    log.info(“邮箱验证码发送成功”);
    // 将验证码放入redis
    boolean set = redisUtil.set(mailNumber + FinalCode.REDIS_Mail_SMS, randCode, FinalCode.SECOND_NUMBER);
    if (set) {
    log.info(“短信验证码缓存成功”);
    }
    sendMessage = “邮箱验证码发送成功”;
    }
    return sendMessage;
    }
登录验证
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Java收取QQ邮箱的代码示例: ```java import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; public class QQMailReceiver { public static void main(String[] args) { String host = "imap.qq.com"; // QQ邮箱的IMAP服务器地址 String username = "[email protected]"; // QQ邮箱账号 String password = "your_qq_email_password"; // QQ邮箱密码 Properties props = new Properties(); props.setProperty("mail.store.protocol", "imap"); props.setProperty("mail.imap.host", host); props.setProperty("mail.imap.port", "993"); props.setProperty("mail.imap.ssl.enable", "true"); try { Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imap"); store.connect(host, username, password); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); Message[] messages = inbox.getMessages(); for (Message message : messages) { System.out.println("From: " + InternetAddress.toString(message.getFrom())); System.out.println("Subject: " + message.getSubject()); System.out.println("Sent Date: " + message.getSentDate()); System.out.println("Message: "); System.out.println(message.getContent().toString()); } inbox.close(false); store.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 其中,需要替换的部分包括: - `host`:QQ邮箱的IMAP服务器地址,一般为`imap.qq.com`。 - `username`:QQ邮箱账号,需要替换为自己的QQ邮箱账号。 - `password`:QQ邮箱密码,需要替换为自己的QQ邮箱密码。 此代码使用JavaMail API实现了收取QQ邮箱的功能。具体步骤包括: 1. 创建一个`Properties`对象,设置IMAP协议相关的参数。 2. 创建一个`Session`对象,用于连接IMAP服务器。 3. 通过`Session`对象获取`Store`对象,用于连接邮箱账号。 4. 打开收件箱`INBOX`,获取其中的所有邮件。 5. 遍历所有邮件,输出邮件的发件人、主题、发送时间和内容。 6. 关闭收件箱和邮箱连接。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值