【亲测可用】阿里云短信

 

   <!--阿里云-短信-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>dysmsapi20170525</artifactId>
            <version>3.0.0</version>
        </dependency>
        <!--阿里云-短信-->

  

 

 

package org.example;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;

import java.util.Objects;

/**
 * 阿里云短信
 */
public class aliyunSMS {


    /**
     * 阿里云 短信 初始化Client
     */
    public static Client newClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = endpoint;
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static void main(String[] args) throws Exception {
        //第一步:在https://dysms.console.aliyun.com/domestic/text中生成签名、模板并审核通过,
        //第二步:加入参数发送短信:
        //name key忘记,请在:【头像】-->【AccessKey管理】重新加入生成一个
        String smsAccessKeyId = "";//name
        String smsAccessKeySecret = "";//key
        String smsEndpoint = "dysmsapi.aliyuncs.com";//阿里云短信域名  固定不变
        String smsSignName = "";//签名名称
        String smsTemplateCode = "";//签名的模板CODE
        String phones = "";//手机号码
        String phonecode = "";//动态码


        Client client = newClient(smsAccessKeyId, smsAccessKeySecret, smsEndpoint);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(smsSignName)
                .setTemplateCode(smsTemplateCode)
                .setPhoneNumbers(phones)
                .setTemplateParam("{\"code\":\"" + phonecode + "\"}");
        try {
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            if (Objects.nonNull(sendSmsResponse) && sendSmsResponse.getBody().code.equals("OK")) {
                System.out.println("短信发送成功。");
            }
        } catch (TeaException error) {
            System.out.println("阿里云短信发送异常: " + error.message);
        }
    }


}

  

posted @ 2024-10-18 15:41  刘贵庆  阅读(7)  评论(0编辑  收藏  举报