Send SMS using AWS SNS - .Net Core

2019-07-23 14:58发布

问题:

I'm trying to use AWS world wide messaging service using C#/.Net Core.

However I do not receive the message in my phone number. Below is the code:

public static async Task<PublishResponse> sendSMS()
        {

            string accessKey = "my Key";
            string secretAccessKey = "my secret key";
            var client = new AmazonSimpleNotificationServiceClient(accessKey, 
            secretAccessKey, RegionEndpoint.USEast1);

            string phoneNumber = "my number";

            PublishRequest req = new PublishRequest();
            req.Message = "Hellloooo from core";
            req.PhoneNumber = "+2" + phoneNumber;   
            PublishResponse res = await client.PublishAsync(req);
            return res;
        }

And I invoke this method in the main function:

 public static void Main(string[] args)
        {
             var respond = sendSMS();     
        }

I appreciate if anyone could help me with this. thanks in advance

回答1:

 public static async Task<PublishResponse> SendMessageToMobileAsync(string countryCode, string mobileNumber, string message)
    {
        var accessKey = "xxx";
        var secretKey = "xxx";
        var client = new AmazonSimpleNotificationServiceClient(accessKey, secretKey, RegionEndpoint.USEast1);
        var messageAttributes = new Dictionary<string, MessageAttributeValue>();
        var smsType = new MessageAttributeValue
        {
            DataType = "String",
            StringValue = "Transactional"
        };

        messageAttributes.Add("AWS.SNS.SMS.SMSType", smsType);
        
        PublishRequest request = new PublishRequest
        {
            Message = message,
            PhoneNumber = countryCode + mobileNumber,
            MessageAttributes = messageAttributes
        };

        return await client.PublishAsync(request);

    }