阿里云国际短信工具类
Joel
发布于 2022-06-14 / 949 阅读 / 0 评论 / 94 点赞

阿里云国际短信工具类

阿里云发送国际短信的Java工具类

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.util.ObjectUtils;

/**
 * @Description 阿里云国际短信发送工具类
 */
public class SmsGlobeUtils {

    // 产品名称:云通信短信API产品,开发者无需替换
    private static final String product = "Dysmsapi";
    // 产品域名,开发者无需替换
    private static final String domain = "dysmsapi.aliyuncs.com";

    // 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    private static final String accessKeyId = "";
    private static final String accessKeySecret = "";


    /**
     * 发送短信
     *
     * @param areaCode 国际区号
     * @param mobiles  手机号码
     * @param senderId 某些地区发送需要senderId
     * @param msg      信息内容
     * @return
     * @throws ServerException
     * @throws ClientException
     */
    public static CommonResponse sendSms(String areaCode, String mobiles, String senderId, String msg) throws ClientException {
        //初始化acsClient,<accessKeyId>和<accessSecret>"在短信控制台查询即可
        DefaultProfile profile = DefaultProfile.getProfile("ap-southeast-1", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        //域名,请勿修改
        request.setSysDomain("dysmsapi.ap-southeast-1.aliyuncs.com");
        //API版本号,请勿修改
        request.setSysVersion("2018-05-01");
        //API名称
        request.setSysAction("SendMessageToGlobe");
        //接收号码,格式为:国际码+号码,必填
        request.putQueryParameter("To", areaCode + mobiles);
        //发送方senderId,选填
        if (!ObjectUtils.isEmpty(senderId)) request.putQueryParameter("From", senderId);
        //短信内容,必填
        request.putQueryParameter("Message", msg);
        CommonResponse response = client.getCommonResponse(request);
        System.out.println(response.getData());
        return response;
    }

   
}

评论