JAVA //七牛云上传//阿里云上传//发送邮件//短信验证码//钉钉消息

package com.example.semd_Msg;

import cn.hutool.core.util.RandomUtil;
import org.junit.Test;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import java.text.SimpleDateFormat;
import java.util.Properties;


import java.util.*;


@SpringBootApplication
public class SemdMsgApplication {


    public static byte[] ImageToBase64ByLocal(String imgFile) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;

        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);

            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        //String base64encodedString = Base64.getEncoder().encodeToString(data);
        return data;// 返回Base64编码过的字节数组字符串
    }

    public static String generateFilePath(String fileName){
        //根据日期生成路径   2022/1/15/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd/");
        String datePath = sdf.format(new Date());
        //uuid作为文件名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //后缀和文件后缀一致
        int index = fileName.lastIndexOf(".");
        // test.jpg -> .jpg
        String fileType = fileName.substring(index);
        return new StringBuilder().append(datePath).append(uuid).append(fileType).toString();
    }

    @Test
    public void qiniu_oss() throws IOException {    //七牛云上传
        InputStream inputStream = this.getClass().getResourceAsStream("/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
//        System.out.println("==============================================");
//        String property = properties.getProperty("qiniu.oss.accessKey");
//        System.out.println("property = " + property);

        String accessKey=properties.getProperty("qiniu.oss.accessKey");
        String secretKey=properties.getProperty("qiniu.oss.secretKey");
        String bucket=properties.getProperty("qiniu.oss.bucket");
        String region=properties.getProperty("qiniu.oss.region");

        //System.out.println(region);

        QiniuUtils upload=new QiniuUtils(accessKey,secretKey,bucket,region);
        byte imgstr[]= ImageToBase64ByLocal("C:\\Users\\Administrator\\Desktop\\1709880952768.png");
        //System.out.printf(imgstr);
//        String newName = generateFilePath("52768.png");     //"\cc\\"+System.currentTimeMillis() + "_" + "52768.png";
//        String data=upload.upload2Qiniu(imgstr,newName);  //上传文件流
//        System.out.printf(data);
        //  String data=upload.upload2Qiniu("123","1.txt");  //上传文本
        //   System.out.printf(data);

//        List<String> ss=upload.get_File_list();   //获取文件列表
//        System.out.println(ss);
//
//        if(upload.del_File("2024-03-13/148b877cc2814da3893b8e302ffa2808.png")){
//            System.out.println("删除成功");
//        }else{
//            System.out.println("删除失败");
//        }
    }


    @Test
    public void ali_oss() throws IOException {    //阿里云上传
        InputStream inputStream = this.getClass().getResourceAsStream("/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
//        System.out.println("==============================================");
//        String property = properties.getProperty("qiniu.oss.accessKey");
//        System.out.println("property = " + property);

        String bucketName=properties.getProperty("aliyun.oss.bucketName");
        String endpoint=properties.getProperty("aliyun.oss.endpoint");
        String accessKeyId=properties.getProperty("aliyun.oss.accessKeyId");
        String accessKeySecret=properties.getProperty("aliyun.oss.accessKeySecret");

        byte imgstr[]= ImageToBase64ByLocal("C:\\Users\\Administrator\\Desktop\\1709880952768.png");
        //System.out.printf(imgstr);

        AliOssUtils aliOssUtil=new AliOssUtils(bucketName,endpoint,accessKeyId,accessKeySecret);

        String vv=aliOssUtil.upload(imgstr,generateFilePath("52768.png"));  //上传图片
        System.out.println(vv);

//        byte[] uploadBytes = "12343455566666".getBytes("utf-8");
//        String vv=aliOssUtil.upload(uploadBytes,generateFilePath("52768.txt"));  //上传文本
//        System.out.println(vv);

        List<String> file_list =aliOssUtil.get_File_list();
        System.out.println(file_list);

        if(aliOssUtil.del_File("2024-03-13/15b7172404534ed084f023f7170a5452.png")){
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }

    }


    @Test
    public void mail() throws IOException {    //发送邮件

        InputStream inputStream = this.getClass().getResourceAsStream("/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
//        System.out.println("==============================================");

        String setHost=properties.getProperty("mail.setHost");
        String setPort=properties.getProperty("mail.setPort");
        String setFrom=properties.getProperty("mail.setFrom");
        String setUser=properties.getProperty("mail.setUser");
        String setPass=properties.getProperty("mail.setPass");

        SendMailUtils sendMailUtils=new SendMailUtils(setHost,Integer.valueOf(setPort),true,setFrom,setUser,setPass);
        sendMailUtils.send_Mail("7650371@qq.com","标题","内容",false);


    }

    @Test
    public void telsms() throws IOException {    //短信验证码
        int code = RandomUtil.randomInt(1000,10000);
        AilSmsUtils.send_code("f4c8c19506d1caf13","CST_ptdie100", "185957", String.valueOf(code));
    }

    @Test
    public void dingtalk() throws IOException {   //钉钉消息
        String access_token="9b8c0127fe7c9d4495945a3b2f321cf5f56";
        String msgtype="markdown";
        String title="111益达律师所邀请您审核采购单";
        String content="看编号:的订单 ![screenshot](https://pic.3gbizhi.com/uploads/20231129/0750e85fa5fd97e19dfb879770d7f7db.jpg)";
        AilDingtalkUtils.send_text_msg(access_token,msgtype,title,content);
    }


    public static void main(String[] args) throws IOException {
        //SpringApplication.run(SemdMsgApplication.class, args);
        //发送验证码

    }

}
#七牛云存储
qiniu.oss.accessKey:MZCNLPwdrNY8
qiniu.oss.secretKey:RcFIFatRj9VWlw1qQB6LPo
qiniu.oss.bucket:xiaos
qiniu.oss.region:huado


# 配置阿里云OSS
aliyun.oss.bucketName:xiaos
aliyun.oss.endpoint:oss-cn-shenzhen.aliyuncs.com
aliyun.oss.accessKeyId:LTAI5tFY7Fynyh
aliyun.oss.accessKeySecret:utyuE1SWCSQC

#配置邮件服务器
mail.setHost:smtp.aliyun.com
mail.setPort:25
mail.setFrom:QQ71@aliyun.com
mail.setUser:QQ71@aliyun.com
mail.setPass:Pl12@
package com.example.semd_Msg;


import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

//钉钉群消息推送
//https://open.dingtalk.com/document/robots/custom-robot-access
public class AilDingtalkUtils {
    public static boolean send_text_msg(String access_token, String msgtype,String title,String content)
    {
        String url="https://oapi.dingtalk.com/robot/send?access_token="+access_token;
        JSONObject js = new JSONObject();
        js.set("msgtype",msgtype);  //"markdown"
        js.set("markdown",new JSONObject().set("title",title).set("text",content));
//        js.set("at",new JSONObject().set("atMobiles",new JSONArray().set("15639216172")));
        js.set("at",new JSONObject().set("isAtAll",true));
        String s = JSONUtil.toJsonStr(js);
        String result = HttpRequest.post(url).body(s).execute().body();
        System.out.printf(result);
        JSONObject object = JSONUtil.parseObj(result);
        if(object.get("errmsg").equals("ok")){
            return true;
        }


        return false;
    }

}
package com.example.semd_Msg;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class AilSmsUtils {


    public static boolean send_code(String appcode,String template_id, String tel,String code) {
        try {
            String url = "https://dfsns.market.alicloudapi.com/data/send_sms";
            //String appcode = "363efa0e07bb4c368b05f500db153ec5";
            //int code = RandomUtil.randomInt(1000,10000);
            String result = HttpRequest.post(url)
                    .header("Authorization", "APPCODE "+appcode)
                    .body("content=code:"+code+"&template_id="+template_id+"&phone_number="+tel)
                    .execute().body();

            JSONObject object = JSONUtil.parseObj(result);
            if(!object.get("status").equals("OK")){
                //log.error("发送验证码错误:{}",object.get("reason"));
                System.out.printf("发送验证码错误:{}",object.get("reason"));
                //throw new BizException(404,"发送验证码错误");
                return false;
            }
            return true;
        } catch (Exception ce) {return false;}

    }


}
package com.example.semd_Msg;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * 七牛云工具类
 */
public class QiniuUtils {
    public  String accessKey;
    public  String secretKey;
    public  String bucket;

    //构造一个带指定 Region 对象的配置类
    public  Configuration cfg;


    //https://developer.qiniu.com/kodo/1239/java#rs-list
    public QiniuUtils(  String accessKey, String secretKey, String bucket,String region) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.bucket = bucket;
        //        华东	Region.region0(), Region.huadong()
//        华北	Region.region1(), Region.huabei()
//        华南	Region.region2(), Region.huanan()
//        北美	Region.regionNa0(), Region.beimei()
//        东南亚	Region.regionAs0(), Region.xinjiapo()
        if (region=="") {
            if (region == "huadong") {
                this.cfg = new Configuration(Region.huadong());
            }
            if (region == "huabei") {
                this.cfg = new Configuration(Region.huabei());
            }
            if (region == "huanan") {
                this.cfg = new Configuration(Region.huanan());
            }
            if (region == "beimei") {
                this.cfg = new Configuration(Region.beimei());
            }
            if (region == "xinjiapo") {
                this.cfg = new Configuration(Region.xinjiapo());
            }
        }else{
            this.cfg = new Configuration(Region.huadong());
        }
        this.cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        this.cfg.resumableUploadMaxConcurrentTaskCount = 2;  // 设置分片上传并发,1:采用同步上传;大于1:采用并发上传
    }

    public String upload2Qiniu(String filePath, String fileName){
        try {
            //...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(this.cfg);
            byte[] uploadBytes = filePath.getBytes("utf-8");
            Auth auth = Auth.create(this.accessKey, this.secretKey);
            String upToken = auth.uploadToken(this.bucket);
            try {
                Response response = uploadManager.put(uploadBytes, fileName, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                //System.out.println(putRet.key);
                //System.out.println(putRet.hash);
                return putRet.key;
            } catch (QiniuException ex) {
                ex.printStackTrace();
                if (ex.response != null) {
                    System.err.println(ex.response);
                    try {
                        String body = ex.response.toString();
                        System.err.println(body);
                    } catch (Exception ignored) {
                    }
                }
            }
        } catch (Exception ex) {
            //ignore
        }

        return "";
    }

    //上传文件
    public  String upload2Qiniu(byte[] bytes, String fileName){
        try {
            //...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(this.cfg);

            //默认不指定key的情况下,以文件内容的hash值作为文件名
            String key = fileName;
            Auth auth = Auth.create(this.accessKey, this.secretKey);
            String upToken = auth.uploadToken(this.bucket);
            try {
                Response response = uploadManager.put(bytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
    //            System.out.println(putRet.key);
    //            System.out.println(putRet.hash);
                return putRet.key;
            } catch (QiniuException ex) {
                ex.printStackTrace();
                if (ex.response != null) {
                    System.err.println(ex.response);
                    try {
                        String body = ex.response.toString();
                        System.err.println(body);
                    } catch (Exception ignored) {
                    }
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return "";
    }


    public List<String> get_File_list(){
        List<String> file_list = new ArrayList<String>();
        try {
            //文件名前缀
            String prefix = "";
            //每次迭代的长度限制,最大1000,推荐值 1000
            int limit = 1000;
            //指定目录分隔符,列出所有公共前缀(模拟列出目录效果)。缺省值为空字符串
            String delimiter = "";
            //列举空间文件列表
            //默认不指定key的情况下,以文件内容的hash值作为文件名
            Auth auth = Auth.create(this.accessKey, this.secretKey);
            BucketManager bucketManager = new BucketManager(auth, this.cfg);

            BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, prefix, limit, delimiter);
            while (fileListIterator.hasNext()) {
                //处理获取的file list结果
                FileInfo[] items = fileListIterator.next();
                for (FileInfo item : items) {
                        file_list.add(item.key);
//                    System.out.println("--------------");
//                    System.out.println(item.key);
//                    System.out.println(item.hash);
//                    System.out.println(item.fsize);
//                    System.out.println(item.mimeType);
//                    System.out.println(item.putTime);
//                    System.out.println(item.endUser);
                }
            }
        } catch (Exception ex) {
        }
        return file_list;
    }

    //删除文件
    public boolean del_File(String fileName){
        String key = fileName;
        Auth auth = Auth.create(this.accessKey, this.secretKey);
        BucketManager bucketManager = new BucketManager(auth, this.cfg);
        try {
            bucketManager.delete(this.bucket, key);
            return true;
        } catch (QiniuException ex) {
            //如果遇到异常,说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
            return false;
        }
    }
}
package com.example.semd_Msg;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.aliyun.oss.ClientException;

public class SendMailUtils {
    private MailAccount account;

    public SendMailUtils(String setHost,Integer setPort, boolean setAuth, String setFrom, String setUser, String setPass) {
        account = new MailAccount();
        account.setHost(setHost);  //邮件服务器的SMTP地址,可选,默认为smtp.<发件人邮箱后缀>
        account.setPort(setPort);  //邮件服务器的SMTP端口,可选,默认25
        account.setAuth(setAuth);
        account.setFrom(setFrom);  //发件人(必须正确,否则发送失败)
        account.setUser(setUser);  //用户名,默认为发件人邮箱前缀
        account.setPass(setPass);   //密码(注意,某些邮箱需要为SMTP服务单独设置授权码,详情查看相关帮助)
    }



    public boolean send_Mail(String to, String title, String content,boolean isHtml) {
        try {
         String success=MailUtil.send(account, CollUtil.newArrayList(to), title, content, isHtml);
         return true;
        } catch (Exception ce) {}
        return false;
    }




}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值