private async Task <bool> SendMessage( TwilioSmsCredentials credentials, string toPhoneNumber, string message) { if (string.IsNullOrWhiteSpace(toPhoneNumber)) { throw new ArgumentException("toPhoneNumber was not provided"); } if (string.IsNullOrWhiteSpace(message)) { throw new ArgumentException("message was not provided"); } var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = CreateBasicAuthenticationHeader( credentials.AccountSid, credentials.AuthToken); var keyValues = new List <KeyValuePair <string, string> >(); keyValues.Add(new KeyValuePair <string, string>("To", toPhoneNumber)); keyValues.Add(new KeyValuePair <string, string>("From", credentials.FromNumber)); keyValues.Add(new KeyValuePair <string, string>("Body", message)); var content = new FormUrlEncodedContent(keyValues); var postUrl = string.Format( CultureInfo.InvariantCulture, TwilioSmsEndpointFormat, credentials.AccountSid); var response = await client.PostAsync( postUrl, content).ConfigureAwait(false); if (response.IsSuccessStatusCode) { if (_log != null) { _log.LogDebug("success sending sms message to " + toPhoneNumber); } return(true); } else { if (_log != null) { string responseBody = await response.Content.ReadAsStringAsync(); var logmessage = $"failed to send sms message to {toPhoneNumber} from {credentials.FromNumber} { response.ReasonPhrase } { responseBody }"; _log.LogWarning(logmessage); } return(false); } }
public Task SendSmsAsync(string number, string message) { TwilioSmsCredentials creds = new TwilioSmsCredentials(); creds.AccountSid = _config["TwilioAccountSid"];; creds.AuthToken = _config["TwilioToken"]; creds.FromNumber = _config["TwilioPhone"]; return(SendMessage(creds, number, message)); }