private static void Main()
        {
            var       connectionString = "<connection-string>"; // Find your Communication Services resource in the Azure portal
            SmsClient smsClient        = new SmsClient(connectionString);

            SmsSendResult sendResult = smsClient.Send(
                from: "<from-phone-number>", // Your E.164 formatted from phone number used to send SMS
                to: "<to-phone-number>",     // E.164 formatted recipient phone number
                message: "Hello 👋🏻");

            Console.WriteLine($"Message id {sendResult.MessageId}");

            Response <IReadOnlyList <SmsSendResult> > response = smsClient.Send(
                from: "<from-phone-number>",
                to: new string[] { "<to-phone-number-1>", "<to-phone-number-2>" }, // E.164 formatted recipient phone numbers
                message: "Hello 👋🏻",
                options: new SmsSendOptions(enableDeliveryReport: true)            // OPTIONAL
            {
                Tag = "greeting",                                                  // custom tags
            });

            IEnumerable <SmsSendResult> results = response.Value;

            foreach (SmsSendResult result in results)
            {
                Console.WriteLine($"Sms id: {result.MessageId}");
                Console.WriteLine($"Send Result Successful: {result.Successful}");
            }
        }
コード例 #2
0
        public void EmptyPass()
        {
            SmsClient   client  = new SmsClient(USERNAME, "", URL);
            TextMessage message = new TextMessage();

            Assert.Throws(typeof(AuthorizationFailedException), delegate { client.Send(message, 1, true); });
        }
コード例 #3
0
        public void EmptyUser()
        {
            SmsClient   client  = new SmsClient("", PASSWORD, URL);
            TextMessage message = new TextMessage();

            Assert.Throws(typeof(AuthorizationFailedException), delegate { client.Send(message, 1, true); });
        }
コード例 #4
0
        protected void Send_Click(object sender, EventArgs e)
        {
            Page.Validate();

            if (!Page.IsValid)
            {
                Output.Style.Add("color", "black");
                Output.Text = "-";
                return;
            }

            // Create the client.
            SmsClient client = new SmsClient(USERNAME, PASSWORD, URL);
            // Create new message with one recipient.
            TextMessage textMessage = new TextMessage(Int64.Parse(Recipient.Text), Text.Text);

            try
            {
                // Send the message.
                MessageResponse response = client.Send(textMessage, MAX_SMS_PER_MESSAGE, TEST_MESSAGE);
                // Print the response.
                Output.Style.Add("color", "black");
                Output.Text = response.statusMessage;
                Text.Text   = "";
            }
            catch (Exception ex)
            {
                // Handle exceptions.
                Output.Style.Add("color", "red");
                Output.Text = ex.Message;
            }
        }
コード例 #5
0
        public static void Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
        {
            log.LogInformation(eventGridEvent.Data.ToString());

            SMSReceived smsReceived = JsonConvert.DeserializeObject <SMSReceived>(eventGridEvent.Data.ToString());

            string returnMessage = string.Empty;

            switch (smsReceived.message)
            {
            case "Use Case 1":
                returnMessage = "Results for Use Case 1";
                break;

            case "Use Case 2":
                returnMessage = "Results for Use Case 2";
                break;

            default:
                returnMessage = "I didn't understand";
                break;
            }

            SmsClient smsClient = new SmsClient(Settings.ACSConnectionString);

            smsClient.Send(
                from: new PhoneNumber(Settings.ACSPhoneNumber),
                to: new PhoneNumber(Settings.ConsumerPhoneNumber),
                message: returnMessage,
                new SendSmsOptions {
                EnableDeliveryReport = true
            }                                                                      // optional
                );
        }
コード例 #6
0
ファイル: NotificationService.cs プロジェクト: seddypdx/WLC
        public async static void TextMessageViaCommunicationService(IConfiguration configuration, string PhoneNumber, string Message)
        {
            string connectionString = "endpoint=https://smsforwlctest.communication.azure.com/;accesskey=ir/swruC+focwatNzk+379NVuhj0+UdlUMZ6Qa9mzi+XbNplGJPewqduDUPZwYtweeeuW3YDKwPnbfuvph46pw==";
            string Key      = "ir/swruC+focwatNzk+379NVuhj0+UdlUMZ6Qa9mzi+XbNplGJPewqduDUPZwYtweeeuW3YDKwPnbfuvph46pw==";
            string endPoint = "https://smsforwlctest.communication.azure.com/";

            SmsClient smsClient = new SmsClient(connectionString);

            smsClient.Send(
                from: new Azure.Communication.PhoneNumber("503-816-9054"),
                to: new Azure.Communication.PhoneNumber(PhoneNumber),
                message: Message,
                new SendSmsOptions {
                EnableDeliveryReport = true
            }                                                      // optional

                );


            //var identityResponse = await client.CreateUserAsync();
            //var identity = identityResponse.Value;
            //Console.WriteLine($"\nCreated an identity with ID: {identity.Id}");

            //// Issue an access token with the "voip" scope for an identity
            //var tokenResponse = await client.IssueTokenAsync(identity, scopes: new[] { CommunicationTokenScope.VoIP });
            //var token = tokenResponse.Value.Token;
            //var expiresOn = tokenResponse.Value.ExpiresOn;
            //Console.WriteLine($"\nIssued an access token with 'voip' scope that expires at {expiresOn}:");
            //Console.WriteLine(token);
        }
コード例 #7
0
        static void Main(string[] args)
        {
            // Create the client.
            SmsClient client = new SmsClient("username", "password", "https://api.websms.com/json");

            // Create new message with one recipient.
            TextMessage textMessage = new TextMessage(4367612345678, "Hello World!");

            try
            {
                // If test = true, it's just a test. No real sms will be sent.
                bool test = false;

                // Send the message.
                MessageResponse response = client.Send(textMessage, 1, test);
                // Print the response.
                Console.WriteLine("Status message: " + response.statusMessage);
                Console.WriteLine("Status code: " + response.statusCode);
            }
            catch (Exception ex)
            {
                // Handle exceptions.
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();

            Console.WriteLine("Hello World!");
        }
コード例 #8
0
        public void send_sms()
        {
            var smsClient = new SmsClient("**", "**");
            var result    = smsClient.Send(ActionTypes.SmsToConcat, "Test mesajı", new List <string> {
                "5055257622"
            }, "MDEV DEMO");

            Console.WriteLine(result);
        }
コード例 #9
0
        public void NoRecipientAddressList()
        {
            SmsClient client = new SmsClient(USERNAME, PASSWORD, URL);

            long[]      recipientAddressList = new long[0];
            TextMessage message = new TextMessage(recipientAddressList, "Hello");

            Assert.Throws(typeof(ParameterValidationException), delegate { client.Send(message, 1, true); });
        }
コード例 #10
0
        public void WrongCredentials()
        {
            SmsClient client = new SmsClient("user", "pass", URL);

            long[] recipientAddressList = new long[1];
            recipientAddressList[0] = 1234567;
            TextMessage message = new TextMessage(recipientAddressList, "Hello");

            Assert.Throws(typeof(AuthorizationFailedException), delegate { client.Send(message, 1, true); });
        }
コード例 #11
0
        public void HttpConnectionException()
        {
            SmsClient client = new SmsClient(USERNAME, PASSWORD, "Not an url");

            long[] recipientAddressList = new long[1];
            recipientAddressList[0] = 1234567;
            TextMessage message = new TextMessage(recipientAddressList, "Hello");

            Assert.Throws(typeof(HttpConnectionException), delegate { client.Send(message, 1, true); });
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: varunalla/Communication
        private static void Main()
        {
            const string connectionString = "YOUR_CONNECTION_STRING"; // Acquire from your Azure Communication resource in the Azure portal
            var          smsClient        = new SmsClient(connectionString);
            var          response         = smsClient.Send(
                from: new PhoneNumber("+1YOUR-PHONE-NUMBER"), // Acquire phone number on your Azure Communication resource
                to: new PhoneNumber("+12222222222"),
                message: "Hello 👋🏻");

            Console.WriteLine($"Message id {response.Value.MessageId}");
        }
コード例 #13
0
        public void ApiException()
        {
            SmsClient client = new SmsClient(USERNAME, PASSWORD, URL);

            long[] recipientAddressList = new long[1];
            recipientAddressList[0] = 1234567;
            TextMessage message = new TextMessage(recipientAddressList, "Hello");

            message.priority = 999999;
            Assert.Throws(typeof(ApiException), delegate { client.Send(message, 1, true); });
        }
コード例 #14
0
        public void send_sms()
        {
            //var smsClient = new SmsClient("karsan-mb1925", "081428");
            // var smsClient = new SmsClient("pelit1-mb1925", "4037");
            var smsClient = new SmsClient("tekiziletisim-mb1925", "8033");
            //var result = smsClient.Send(ActionTypes.SmsToConcat, "Test mesajı", new List<string> { "5313357661" }, "MDEV DEMO");
            var result = smsClient.Send(ActionTypes.Sms, "Test mesajı", new List <string> {
                "5313357661"
            }, "");

            Console.WriteLine(result);
        }
        public SmsSendResult SendSms(Uri resourceEndpoint, string from, string to, string message)
        {
            SmsClient     smsClient  = new SmsClient(resourceEndpoint, this.credential);
            SmsSendResult sendResult = smsClient.Send(
                from: from,
                to: to,
                message: message,
                new SmsSendOptions(enableDeliveryReport: true)  // optional
                );

            return(sendResult);
        }
コード例 #16
0
        public void Send(SmsMessage smsMessage)
        {
            var smsClient = new SmsClient(_options.ConnectionString);
            var response  = smsClient.Send(
                from: new PhoneNumber(_options.FromNumber),
                to: new PhoneNumber(smsMessage.PhoneNumber),
                message: smsMessage.Message);

            if (!string.IsNullOrWhiteSpace(response?.Value?.MessageId))
            {
            }
        }
コード例 #17
0
    static void Main()
    {
        // Create the client.
        SmsClient client = new SmsClient("username", "password", "https://api.websms.com/json");

        // Create array with multiple recipients.
        long[] recipients = new long[3];
        recipients[0] = 1000001;
        recipients[1] = 1000002;
        recipients[2] = 1000003;

        // Binary message - Create concatenated SMS using a user data header
        // (http://en.wikipedia.org/wiki/Concatenated_SMS)

        byte[][]  data = new byte[2][];
        ArrayList tmp  = new ArrayList(new byte[] { 0x05, 0x00, 0x03, 0xCC, 0x02, 0x01 });

        tmp.AddRange(Encoding.UTF8.GetBytes("Hello "));
        data[0] = (byte[])tmp.ToArray(typeof(byte));
        tmp     = new ArrayList(new byte[] { 0x05, 0x00, 0x03, 0xCC, 0x02, 0x02 });
        tmp.AddRange(Encoding.UTF8.GetBytes("World!"));
        data[1] = (byte[])tmp.ToArray(typeof(byte));

        BinaryMessage binaryMessage = new BinaryMessage(recipients, data);

        binaryMessage.userDataHeaderPresent = true;

        Thread thread = new Thread(delegate()
        {
            try
            {
                // If test = true, it's just a test. No real sms will be sent.
                bool test = false;

                // Send the message.
                MessageResponse response = client.Send(binaryMessage, test);
                // Print the response.
                Console.WriteLine("Status message: " + response.statusMessage);
                Console.WriteLine("Status code: " + response.statusCode);
            }
            catch (Exception ex)
            {
                // Handle exceptions.
                Console.WriteLine(ex.Message);
            }
        });

        thread.Start();
        thread.Join();
        Console.ReadKey();
    }
コード例 #18
0
        public Task <string> SendNewMessageAsync(MessageThread thread, Message message, string acsConnectionString, string dbConnectionString)
        {
            SmsClient smsClient;
            string    response = String.Format("Message to {0} send at {1}", message.To, message.Date);

            if (String.IsNullOrEmpty(acsConnectionString))
            {
                throw new NullReferenceException("The connection string to Azure Communication Services is not set.");
            }

            try
            {
                // TODO: Address formating of numbers correctly. Numbers require the + in the SmsClient API, but are
                // received in the EventGrid payload without the + so makes matching difficult.

                smsClient = new SmsClient(acsConnectionString);
                var smsResult = smsClient.Send(
                    from: new PhoneNumber(String.Format("+{0}", message.From)),
                    to: new PhoneNumber(String.Format("+{0}", message.To)),
                    message: message.Body
                    );

                message.ID = smsResult.Value.MessageId;
                thread.Messages.Add(message);

                response = String.Format("{0} with ID {1}", response, message.ID);

                using (var db = new MessageThreadDbContext(dbConnectionString))
                {
                    db.Entry(thread).State = EntityState.Modified;
                    db.MessageThreads.Update(thread);

                    db.Entry(message).State = EntityState.Added;
                    db.Messages.Add(message);

                    db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                response = String.Format("Unable to send SMS message: {0}", e.Message);
            }
            finally
            {
                smsClient = null;
            }

            return(Task.FromResult <string>(response));
        }
コード例 #19
0
        public void SendingSMSMessage()
        {
            SmsClient smsClient = CreateSmsClient();

            #region Snippet:Azure_Communication_Sms_Tests_Send
            SmsSendResult sendResult = smsClient.Send(
                //@@ from: "<from-phone-number>", // Your E.164 formatted from phone number used to send SMS
                //@@ to: "<to-phone-number>", // E.164 formatted recipient phone number
                /*@@*/ from: TestEnvironment.FromPhoneNumber,
                /*@@*/ to: TestEnvironment.ToPhoneNumber,
                message: "Hi");
            Console.WriteLine($"Sms id: {sendResult.MessageId}");
            #endregion Snippet:Azure_Communication_Sms_Tests_SendAsync
            Console.WriteLine($"Send Result Successful: {sendResult.Successful}");
        }
コード例 #20
0
        public void TextMessage()
        {
            SmsClient client = new SmsClient(USERNAME, PASSWORD, URL);

            long[] recipientAddressList = new long[1];
            recipientAddressList[0] = 1234567;
            TextMessage message = new TextMessage(recipientAddressList, "Hello");

            message.clientMessageId = "clientMessageId";
            MessageResponse response = client.Send(message, 1, true);

            Assert.AreEqual(response.statusCode, StatusCode.OK);
            Assert.AreEqual(response.statusMessage, "OK");
            Assert.AreEqual(response.clientMessageId, "clientMessageId");
        }
コード例 #21
0
        static void Main(string[] args)
        {
            SmsClient smsClient = new SmsClient(Settings.ACSConnectionString);

            smsClient.Send(
                from: new PhoneNumber(Settings.ACSPhoneNumber),
                to: new PhoneNumber(Settings.ConsumerPhoneNumber),
                //message: "Hello World via SMS",
                message: "Azure Functions for the win!!!",
                new SendSmsOptions {
                EnableDeliveryReport = true
            }                                                                      // optional
                );

            Console.WriteLine("Message sent");
        }
コード例 #22
0
        private static Azure.Response <SendSmsResponse> SendSMSAsync(string acsConnectionString, string phoneNumberFrom, string phoneNumberTo, string message)
        {
            var smsClient = new SmsClient(acsConnectionString,
                                          new SmsClientOptions(SmsClientOptions.ServiceVersion.V1));

            var sendSmsResponse = smsClient.Send(
                new PhoneNumber(phoneNumberFrom),
                new PhoneNumber(phoneNumberTo),
                message,
                new SendSmsOptions()
            {
                EnableDeliveryReport = true
            });

            return(sendSmsResponse);
        }
コード例 #23
0
        public override Task <ResourceResponse[]> SendActivitiesAsync(ITurnContext turnContext,
                                                                      Activity[] activities, CancellationToken cancellationToken)
        {
            var responses = new List <ResourceResponse>();

            foreach (var activity in activities)
            {
                if (activity.Type != ActivityTypes.Message)
                {
                    _logger.LogTrace(
                        $"Unsupported Activity Type: '{activity.Type}'. Only Activities of type 'Message' are supported.");
                }
                else
                {
                    var sendSmsRequest = _requestMapper.ActivityToResponse(activity);
                    var smsClient      = new SmsClient(_options.AcsConnectionString,
                                                       new SmsClientOptions(SmsClientOptions.ServiceVersion.V1, _options.RetryOptions));

                    var sendSmsResponse = smsClient.Send(
                        sendSmsRequest.From,
                        sendSmsRequest.To,
                        sendSmsRequest.Message,
                        new SendSmsOptions()
                    {
                        EnableDeliveryReport = sendSmsRequest.EnableDeliveryReport
                    });

                    var response = new ResourceResponse()
                    {
                        Id = sendSmsResponse.Value.MessageId,
                    };

                    responses.Add(response);
                }
            }

            var result = responses.ToArray();

            return(Task.FromResult(result));
        }
コード例 #24
0
        /// <summary>
        /// Sends the specified SMS message.
        /// </summary>
        /// <param name="fromPhoneNumber">The origin phone number</param>
        /// <param name="toPhoneNumber">The destination phone number.</param>
        /// <param name="message">Text of the message to be sent.</param>
        /// <param name="enableDeliveryReport">If set to <c>true</c> the delivery report will be enabled.</param>
        /// <returns>A <c>string</c> representing the sent message identifier.</returns>
        /// <exception cref="ArgumentNullException">
        /// Thrown if <paramref name="fromPhoneNumber"/>, <paramref name="toPhoneNumber"/>,
        /// or <paramref name="message"/> are not specified.
        /// </exception>
        /// <exception cref="Exception">Thrown if the SMS client was not initialized correctly.</exception>
        public string SendSMS(string fromPhoneNumber, string toPhoneNumber, string message, bool enableDeliveryReport = true)
        {
            if (string.IsNullOrWhiteSpace(fromPhoneNumber))
            {
                throw new ArgumentNullException(nameof(fromPhoneNumber));
            }
            if (string.IsNullOrWhiteSpace(toPhoneNumber))
            {
                throw new ArgumentNullException(nameof(toPhoneNumber));
            }
            if (string.IsNullOrWhiteSpace(message))
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (_smsClient is null)
            {
                throw new Exception("The SMS Client was not initialized correctly.");
            }

            Response <SendSmsResponse> response = _smsClient.Send(
                from: new PhoneNumber(fromPhoneNumber),
                to: new PhoneNumber(toPhoneNumber),
                message: message,
                new SendSmsOptions {
                EnableDeliveryReport = enableDeliveryReport
            });

            SMSMessageTableEntity.Save(
                new SMSMessage()
            {
                FromPhoneNumber = _fromPhoneNumber,
                ToPhoneNumber   = toPhoneNumber,
                Message         = message,
                MessageId       = response.Value.MessageId
            }.ToSMSMessageTableEntity(),
                _azureStorageSettings,
                _messageArchiveTable);

            return(response.Value.MessageId);
        }
コード例 #25
0
        public void SendingGroupSMSMessageWithOptions()
        {
            SmsClient smsClient = CreateSmsClient();

            #region Snippet:Azure_Communication_SmsClient_Send_GroupSmsWithOptions
            var response = smsClient.Send(
                //@@ from: "<from-phone-number>", // Your E.164 formatted from phone number used to send SMS
                //@@ to: new string[] { "<to-phone-number-1>", "<to-phone-number-2>" }, // E.164 formatted recipient phone numbers
                /*@@*/ from: TestEnvironment.FromPhoneNumber,
                /*@@*/ to: new string[] { TestEnvironment.ToPhoneNumber, TestEnvironment.ToPhoneNumber },
                message: "Weekly Promotion!",
                options: new SmsSendOptions(enableDeliveryReport: true) // OPTIONAL
            {
                Tag = "marketing",                                      // custom tags
            });
            foreach (SmsSendResult result in response.Value)
            {
                Console.WriteLine($"Sms id: {result.MessageId}");
                Console.WriteLine($"Send Result Successful: {result.Successful}");
            }
            #endregion Snippet:Azure_Communication_SmsClient_Send_GroupSmsWithOptions
        }
コード例 #26
0
        static void Main(string[] args)
        {
            var recipients    = new List <string>();
            var parameters    = new RunnerOnDemandParameters();
            var nearbyRunners = GetNearbyRunners();

            foreach (var runner in nearbyRunners)
            {
                recipients.Add(runner.MobilePhone);
                parameters.Name.Add(runner.MobilePhone, runner.Name);
                parameters.Url.Add(runner.MobilePhone, $"https://foo.se/x/{GenerateToken()}");
            }

            var sms = new Sms {
                To         = recipients.ToArray(),
                From       = "Me",
                Message    = "Hi ${name}! Go here ${url}",
                Parameters = parameters,
            };

            Console.WriteLine(JsonConvert.SerializeObject(sms));
            Task.Run(async() => { await SmsClient.Send(JsonConvert.SerializeObject(sms)); }).Wait();
        }
コード例 #27
0
        public void BinaryMessage()
        {
            SmsClient client = new SmsClient(USERNAME, PASSWORD, URL);

            long[] recipientAddressList = new long[1];
            recipientAddressList[0] = 1234567;
            byte[][]  data = new byte[2][];
            ArrayList tmp  = new ArrayList(new byte[] { 0x05, 0x00, 0x03, 0xCC, 0x02, 0x01 });

            tmp.AddRange(Encoding.UTF8.GetBytes("Hello "));
            data[0] = (byte[])tmp.ToArray(typeof(byte));
            tmp     = new ArrayList(new byte[] { 0x05, 0x00, 0x03, 0xCC, 0x02, 0x02 });
            tmp.AddRange(Encoding.UTF8.GetBytes("World!"));
            data[1] = (byte[])tmp.ToArray(typeof(byte));
            BinaryMessage message = new BinaryMessage(recipientAddressList, data);

            message.clientMessageId = "clientMessageId";
            MessageResponse response = client.Send(message, true);

            Assert.AreEqual(response.statusCode, StatusCode.OK);
            Assert.AreEqual(response.statusMessage, "OK");
            Assert.AreEqual(response.clientMessageId, "clientMessageId");
        }
コード例 #28
0
ファイル: Program.cs プロジェクト: alexhauser/LibSmsGateway
        static void Main(string[] args)
        {
            // Get username and password from secret app settings
            var config = new ConfigurationBuilder()
                         .SetBasePath(System.IO.Directory.GetCurrentDirectory())
                         .AddJsonFile("appsecrets.json", false, true)
                         .Build();

            // Create an SMS client
            var smsClient = new SmsClient(
                config["user"], config["password"]);

            // Send a message
            var result = smsClient.Send(
                message: "This is a test message",  // message text
                recipient: "999999999999",          // destination number
                sender: "SenderName",               // sender name, optional
                group: null,                        // recipient group, optional
                receipt: false,                     // receive confirmation, optional
                flash: false                        // flash sms, optional
                ).Result;

            // Evaluate result
            if (result.IsSuccess)
            {
                // SMS sucesssfully delivered
            }
            else
            {
                // There was an error, find out what happened
                Console.WriteLine(
                    "SatusCode: {0}, StatusMessage: \"{1}\", RawResult:\r\n{2}\r\n",
                    result.StatusCode.ToString(),
                    result.StatusMessage,
                    result.RawResponse);
            }
        }
コード例 #29
0
 public void send_sms()
 {
     var smsClient = new SmsClient("*", "*");
     var result = smsClient.Send(ActionTypes.SmsToConcat, "Test mesaj", new List<string> { "*" }, "*");
     Console.WriteLine(result);
 }