国外Twilio 发送sms短信

private static final String userName = "Account SID";  
private static final String password = "Auth Token"; 
private String fromPhone; //你的手机号(平台购买的手机号)


/**
     * 发送短信
     * */
    public static Map sms(String toPhone) {
        Map mapTypes =  new HashMap();
        try {
            // 生成安全的HS512密钥
            SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS512);
            // 初始化Twilio客户端
            Twilio.init(userName, password);
            // 发送短信
            Message message = Message.creator(
                new PhoneNumber(toPhone), //对方手机号
                new PhoneNumber("+14158141829"),//fromPhone
                "短信内容"
            ).create();
            // 打印短信的SID
            mapTypes =  JSON.parseObject(String.valueOf(message));
            System.out.println(JSON.toJSONString(mapTypes));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mapTypes;
    }

    public static void main(String[] args) {
        Map sms = sms("+14159352345");
    }

//发送邮件

 /**
     * 发送邮件
     * */
    public static Map sendEmail(String toPhone) {
        Map mapTypes =  new HashMap();
        String apiKey = "后台的appkey,详细查看appKey的设置";

        try {
            SendGrid sg = new SendGrid(apiKey);
            Request request = new Request();
            request.setMethod(Method.POST);
            request.setEndpoint("/mail/send");//格式不能改

            // Create mail
            Mail mail = new Mail();
            Personalization personalization1 = new Personalization();
            personalization1.addTo(new Email("收件人邮件地址", "收件人名称"));
            personalization1.addCustomArg("version", "1.0");//注意:自定义参数,会在回调的时候返回
            mail.addPersonalization(personalization1);
            mail.setFrom(new Email("发件人邮箱", "发件人名称"));
                mail.setSubject("Your Example Order Confirmation");
            //内容对象
            Content content = new Content();
            content.setType("text/html");
            content.setValue("

Hello from Twilio SendGrid!

Sending with the email service trusted by developers and marketers for time-savings, scalability, and delivery expertise.

%open-track%

"); mail.addContent(content); request.setBody(mail.build()); //发送邮件 Response response = sg.api(request); System.out.println(response.getStatusCode()); System.out.println(response.getBody()); System.out.println(response.getHeaders()); mapTypes = JSON.parseObject(response.getBody(),Map.class); } catch (Exception e) { e.printStackTrace(); } return mapTypes; }

注意:短信的pom:  


     com.twilio.sdk
     twilio
     7.55.0
 

邮件的我是在官网下载的jar包打到项目里的

你可能感兴趣的:(java,开发语言)