예제 #1
0
파일: SmsSender.cs 프로젝트: Shahlojon/sms
        public async Task <string> Send(string from, string to, string message)
        {
            var conf = new Conf();

            conf.host     = "0.0.0.0"; //это хост смпп сервера
            conf.port     = 0000;      //это порт смпп сервера
            conf.systemId = "test";    //это логин или системный ид смпп позователя
            conf.password = "******";    //это парол смпп позователя

            SmppClient client = new SmppClient();
            await client.Connect(conf.host, conf.port);

            await client.Bind(conf.systemId, conf.password, ConnectionMode.Transceiver);

            var resp = await client.Submit(
                SMS.ForSubmit()
                .From(from, AddressTON.Alphanumeric, AddressNPI.Unknown)
                .To(to, AddressTON.International, AddressNPI.ISDN)
                .Coding(DataCodings.Cyrllic)
                .Text(message)
                );

            if (resp.All(x => x.Header.Status == CommandStatus.ESME_ROK))
            {
                return("Message has been sent.");
            }
            return(resp.GetValue(0).ToString());
        }
예제 #2
0
        // <SendHelloWorld>
        public static async Task SendHelloWorld()
        {
            using (SmppServer server = new SmppServer(new IPEndPoint(IPAddress.Any, 7777)))
            {
                server.Start();

                using (SmppClient client = new SmppClient())
                {
                    if (await client.Connect("localhost", 7777))
                    {
                        BindResp bindResp = await client.Bind("1", "2");

                        if (bindResp.Header.Status == CommandStatus.ESME_ROK)
                        {
                            var submitResp = await client.Submit(
                                SMS.ForSubmit()
                                .From("111")
                                .To("222")
                                .Coding(DataCodings.UCS2)
                                .Text("Hello World!"));

                            if (submitResp.All(x => x.Header.Status == CommandStatus.ESME_ROK))
                            {
                                client.Logger.Info("Message has been sent.");
                            }
                        }

                        await client.Disconnect();
                    }
                }
            }
        }
예제 #3
0
        // <SendHelloWorld>
        public static async Task SendHelloWorld()


        {
            using (SmppClient client = new SmppClient())
            {
                if (await client.Connect("192.168.1.190", 7777))
                {
                    BindResp bindResp = await client.Bind("admin", "admin");

                    if (bindResp.Header.Status == CommandStatus.ESME_ROK)
                    {
                        var submitResp = await client.Submit(
                            SMS.ForSubmit()
                            .From("111")
                            .To("222")
                            .Coding(DataCodings.UCS2)
                            .Text("Hello dude!!"));

                        if (submitResp.All(x => x.Header.Status == CommandStatus.ESME_ROK))
                        {
                            client.Logger.Info("Message has been sent.");
                        }
                    }

                    // await client.Disconnect();
                }
            }
        }
예제 #4
0
        private static async Task SendAsync()
        {
            Console.WriteLine($"INFO: After sending message, please wait for the delivery report to arrived before exiting app. Then, you may unbind & exit by pressing any key.");
            Console.WriteLine("To send a message, enter all required information below");

            GetMsgInput();

            var builder = SMS.ForSubmit().From(from).To(to).Text(textMessage).DeliveryReceipt();

            Console.WriteLine($"Submitting..");
            Stopwatch sw   = Stopwatch.StartNew();
            var       resp = await smppClient.Submit(builder);

            sw.Stop();

            Console.WriteLine($"--Submit finished [Takes {sw.Elapsed}]");
            Console.WriteLine($"----SubmitSmResp: {resp[0]}");

            if (resp[0].Header.Status != CommandStatus.ESME_ROK)
            {
                Console.WriteLine("----Sorry, there are no delivery report for this message. You may press any key now to unbind & exit");
            }

            Console.ReadKey();
            await UnbindAsync();

            appSw.Stop();
            Console.WriteLine($"Runtime: {appSw.Elapsed}");
            Console.WriteLine("#############################");
        }
예제 #5
0
 public static async Task SendText(SmppClient client)
 {
     var resp = await client.Submit(
         SMS.ForSubmit()
         .From("short_code")
         .To("436641234567")
         .Coding(DataCodings.UCS2)
         .Text("test text")
         );
 }
예제 #6
0
 private ISubmitSmBuilder ForSubmit(AnMessage message)
 {
     return(SMS.ForSubmit()
            .ServiceType(anBind.ServiceType)
            .Text(message.text)
            .From(anBind.Tel)
            .To(message.phoneNumber)
            .Coding(message.DataCoding)
            .DeliveryReceipt());
 }
예제 #7
0
 public static async Task SendMessageToApplicationPort(SmppClient client)
 {
     var resp = await client.Submit(
         SMS.ForSubmit()
         .From("short_code")
         .To("436641234567")
         .Text("test")
         .Set(sm => sm.UserData.Headers.Add(new ApplicationPortAddressingScheme16bit(0x1579, 0x0000)))
         );
 }
예제 #8
0
 public void SendSms()
 {
     var response = Client.Submit(SMS.ForSubmit()
                                  .ServiceType("test")
                                  .Text("Only .Net only C#!!!")
                                  .From("QUIZUP")
                                  .To("+37368453453")
                                  .DeliveryReceipt()
                                  .Coding(DataCodings.Default)
                                  );
 }
        //</ConnectToServer>

        //<SendMessage>
        public async Task SendMessage()
        {
            IList <SubmitSmResp> responses = await _client.Submit(
                SMS.ForSubmit()
                .Text("Test Test Test Test Test Test Test Test Test Test")
                .From("1111")
                .To("79171234567")
                .Coding(DataCodings.UCS2)
                .DeliveryReceipt()
                );
        }
예제 #10
0
        public static async Task SendBinary(SmppClient client)
        {
            byte[] data = ByteArray.FromHexString(
                "FFFF002830006609EC592F55DCE9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005C67");

            var resp = await client.Submit(
                SMS.ForSubmit()
                .From("short_code")
                .To("436641234567")
                .Data(data)
                );
        }
        public void SendPSSRResponse()
        {
            string shortCode     = "7777";
            ushort ussdSessionId = 0;
            bool   sessionEnd    = true;

            _client.Submit(SMS.ForSubmit()
                           .ServiceType("USSD")
                           .From(shortCode, AddressTON.NetworkSpecific, AddressNPI.Private)
                           .To("+79171234567")
                           .Text("USSD text")
                           .Coding((DataCodings)0x15)
                           .AddParameter(OptionalTags.UssdServiceOp, new byte[] { 17 }) //PSSR response
                           .AddParameter(OptionalTags.ItsSessionInfo, GetItsSessionInfoValue(ussdSessionId, sessionEnd))
                           );
        }
        public static async Task Run()
        {
            // <Sample>
            using (SmppServer server = new SmppServer(new IPEndPoint(IPAddress.Any, 7777)))
            {
                server.EnabledSslProtocols = SslProtocols.Tls12;
                server.ServerCertificate   = new X509Certificate2("server_certificate.p12", "cert_password");

                server.Start();

                server.evClientConnected += (sender, client) =>
                {
                    var clientCertificate = client.ClientCertificate;
                    //You can validate client certificate and disconnect if it is not valid.
                };

                using (SmppClient client = new SmppClient())
                {
                    client.EnabledSslProtocols = SslProtocols.Tls12;
                    //if required you can be authenticated with client certificate
                    client.ClientCertificates.Add(new X509Certificate2("client_certificate.p12", "cert_password"));

                    if (await client.Connect("localhost", 7777))
                    {
                        BindResp bindResp = await client.Bind("username", "password");

                        if (bindResp.Header.Status == CommandStatus.ESME_ROK)
                        {
                            var submitResp = await client.Submit(
                                SMS.ForSubmit()
                                .From("111")
                                .To("436641234567")
                                .Coding(DataCodings.UCS2)
                                .Text("Hello World!"));

                            if (submitResp.All(x => x.Header.Status == CommandStatus.ESME_ROK))
                            {
                                client.Logger.Info("Message has been sent.");
                            }
                        }

                        await client.Disconnect();
                    }
                }
            }
            //</Sample>
        }
        private void SendAnswerToHuaweiUSSDWithServiceType(DeliverSm deliverSm)
        {
            if (deliverSm.ServiceType == "PSSRR")
            {
                _client.Submit(SMS.ForSubmit()
                               .ServiceType("PSSRC")
                               .To(deliverSm.SourceAddress)
                               .Coding(deliverSm.DataCoding)
                               .Text("USSD response")
                               );
            }

            if (deliverSm.ServiceType == "RELC")
            {
                //USSD Dialogue has been released
            }
        }
        public Task SendCommmand2()
        {
            string shortCode = "7777";

            //     _client.EsmeAddress = new SmeAddress(shortCode, AddressTON.NetworkSpecific, AddressNPI.Private);

            _client.Bind("username", "password", ConnectionMode.Transceiver);


            return(_client.Submit(SMS.ForSubmit()
                                  .From(shortCode, AddressTON.NetworkSpecific, AddressNPI.Private)
                                  .To("+79171234567")
                                  .Text("USSD text")
                                  .Coding(DataCodings.Class1MEMessage8bit)
                                  .AddParameter(new UssdServiceOpParameter(USSDOperation.USSRRequest)) //USSR request
                                  .AddParameter(OptionalTags.ItsSessionInfo, new byte[] { 11 })
                                  ));
        }
        public void SendCommmand3()
        {
            string shortCode = "7777";


            _client.Bind("username", "password", ConnectionMode.Transceiver);


            _client.Submit(SMS.ForSubmit()
                           .ServiceType("USSD")
                           .From(shortCode, AddressTON.NetworkSpecific, AddressNPI.Private)
                           .To("+79171234567")
                           .Text("USSD text")
                           .Coding((DataCodings)0x15)
                           .AddParameter(new UssdServiceOpParameter(USSDOperation.USSRRequest)) //USSR request
                           .AddParameter(0x4001, Encoding.ASCII.GetBytes("111111111111"))       // ussd_imsi
                           );
        }
        public static async Task <int> RunTest(SmppClient client, int messagesNumber)
        {
            List <Task> tasks = new List <Task>();

            Stopwatch watch = Stopwatch.StartNew();

            for (int i = 0; i < messagesNumber; i++)
            {
                tasks.Add(client.Submit(
                              SMS.ForSubmit()
                              .From("111")
                              .To("222")
                              .Coding(DataCodings.UCS2)
                              .Text("test")));
            }

            await Task.WhenAll(tasks);

            watch.Stop();

            return(Convert.ToInt32(messagesNumber / watch.Elapsed.TotalSeconds));
        }
        //<SendMessage>
        public async Task SendMessage(TextMessage message)
        {
            IList <SubmitSm> list = SMS.ForSubmit()
                                    .From(_config.ShortCode)
                                    .To(message.PhoneNumber)
                                    .Text(message.Text)
                                    .DeliveryReceipt()
                                    .Create(_client);

            foreach (SubmitSm sm in list)
            {
                sm.Header.Sequence = _client.SequenceGenerator.NextSequenceNumber();
                _clientMessageStore.SaveSequence(message.Id, sm.Header.Sequence);
            }

            var responses = await _client.Submit(list);

            foreach (SubmitSmResp resp in responses)
            {
                _clientMessageStore.SaveMessageId(message.Id, resp.MessageId);
            }
        }
예제 #18
0
        public static async Task SendSms(string phoneNumber, string smsText)
        {
            string filePath = ConfigurationManager.AppSettings.Get("SMPPLogPath");

            LogManager.SetLoggerFactory(name => new FileLogger(filePath, LogLevel.All));
            using (SmppClient client = new SmppClient())
            {
                try
                {
                    if (await client.Connect(new DnsEndPoint("smpp.server", 7777, AddressFamily.InterNetwork)))
                    {
                        BindResp bindResp = await client.Bind("username", "password");

                        if (bindResp.Header.Status == CommandStatus.ESME_ROK)
                        {
                            var submitResp = await client.Submit(
                                SMS.ForSubmit()
                                .From("short code")
                                .To(phoneNumber)
                                .Coding(DataCodings.UCS2)
                                .Text(smsText));

                            if (submitResp.All(x => x.Header.Status == CommandStatus.ESME_ROK))
                            {
                                client.Logger.Info("Message has been sent.");
                            }
                        }

                        await client.Disconnect();
                    }
                }
                catch (Exception ex)
                {
                    client.Logger.Error("Failed send message", ex);
                }
            }
        }
        private async Task SubmitBatchMessages()
        {
            var sourceAddress = new SmeAddress(tbSrcAdr.Text, (AddressTON)byte.Parse(tbSrcAdrTON.Text), (AddressNPI)byte.Parse(tbSrcAdrNPI.Text));

            var destinationAddress = new SmeAddress(tbDestAdr.Text, (AddressTON)byte.Parse(tbDestAdrTON.Text), (AddressNPI)byte.Parse(tbDestAdrNPI.Text));


            string messageText = tbMessageText.Text;

            SubmitMode mode = GetSubmitMode();

            DataCodings coding = GetDataCoding();

            int count = int.Parse(tbRepeatTimes.Text);

            _log.Info("Submit message batch. Count: {0}. Text: {1}", count, messageText);

            // bulk sms test
            List <SubmitSm> batch = new List <SubmitSm>();

            for (int i = 0; i < count; i++)
            {
                ISubmitSmBuilder builder = SMS.ForSubmit()
                                           .Text(messageText)
                                           .From(sourceAddress)
                                           .To(destinationAddress)
                                           .Coding(coding);

                switch (mode)
                {
                case SubmitMode.Payload:
                    builder.MessageInPayload();
                    break;

                case SubmitMode.ShortMessageWithSAR:
                    builder.ConcatenationInSAR();
                    break;
                }

                batch.AddRange(builder.Create(_client));
            }



            try
            {
                Stopwatch watch = Stopwatch.StartNew();

                var resp = (await _client.Submit(batch)).ToArray();

                watch.Stop();

                if (resp.All(x => x.Header.Status == CommandStatus.ESME_ROK))
                {
                    _log.Info("Batch sending completed. Submitted: {0}, Elapsed: {1} ms, Performance: {2} m/s", batch.Count, watch.ElapsedMilliseconds, batch.Count * 1000f / watch.ElapsedMilliseconds);
                }
                else
                {
                    var wrongStatuses = resp.Where(x => x.Header.Status != CommandStatus.ESME_ROK)
                                        .Select(x => x.Header.Status).Distinct();

                    _log.Warn("Submit failed. Wrong Status: {0}", string.Join(", ", wrongStatuses));
                }
            }
            catch (Exception ex)
            {
                _log.Error("Submit failed. Error: {0}", ex.Message);
            }
        }
예제 #20
0
        public static int SendSMS(SmsModel sms)
        {
            bool IsConnected = SmppHelper.smppClient.Connected;

            if (!IsConnected)
            {
                IList <SmppModel> listSMPP = new List <SmppModel>();

                if (!String.IsNullOrEmpty(sms.SMPP_IP_1))
                {
                    listSMPP.Add(new SmppModel()
                    {
                        HOST_NAME = sms.SMPP_IP_1,
                        PORT      = String.IsNullOrEmpty(sms.SMPP_PORT_1) ? 0 : Convert.ToInt32(sms.SMPP_PORT_1),
                        ADDR_TON  = Convert.ToByte("1"),
                        ADDR_NPI  = Convert.ToByte("1"),
                        SYSTEM_ID = sms.SMPP_USER,
                        PASSWORD  = sms.SMPP_PASS
                    });
                }

                if (!String.IsNullOrEmpty(sms.SMPP_IP_2))
                {
                    listSMPP.Add(new SmppModel()
                    {
                        HOST_NAME = sms.SMPP_IP_2,
                        PORT      = String.IsNullOrEmpty(sms.SMPP_PORT_2) ? 0 : Convert.ToInt32(sms.SMPP_PORT_2),
                        ADDR_TON  = Convert.ToByte("1"),
                        ADDR_NPI  = Convert.ToByte("1"),
                        SYSTEM_ID = sms.SMPP_USER,
                        PASSWORD  = sms.SMPP_PASS
                    });
                }

                IsConnected = SmppHelper.ConnectSMPP(listSMPP);
            }

            if (IsConnected && SmppHelper.smppClient.Connected)
            {
                IList <SubmitSmResp> response = SmppHelper.smppClient.Submit(
                    SMS.ForSubmit()
                    .From(sms.SENDER_NAME.Trim())
                    .To(sms.PHONE.Trim()).Coding(DataCodings.Default)
                    .Text(sms.SMS_CONTENT.Trim())
                    .DeliveryReceipt());

                if (response.All(x => x.Status == CommandStatus.ESME_ROK))
                {
                    logger.Info(AppConst.A("SendSMS_SMPP", sms.SENDER_NAME, sms.PHONE, sms.SMS_CONTENT, response[0].Status, response[0].MessageId, response[0].Request));
                    return(AppConst.SYS_ERR_OK);
                }
                else
                {
                    logger.Info(AppConst.A("SendSMS_SMPP", response[0].MessageId, response[0].Request));
                    return((int)response[0].Status);
                }
            }
            else
            {
                logger.Info(AppConst.A("SendSMS_SMPP", "Connect SMPP fail!", "Switch send SMS to API"));
                return(AppConst.SYS_ERR_EXCEPTION);
            }
        }
        private void client_evDeliverSm(object sender, DeliverSm data)
        {
            try
            {
                //Check if we received Delivery Receipt
                if (data.MessageType == MessageTypes.SMSCDeliveryReceipt)
                {
                    //Get MessageId of delivered message
                    string       messageId      = data.Receipt.MessageId;
                    MessageState deliveryStatus = data.Receipt.State;

                    _log.Info("Delivery Receipt received: {0}", data.Receipt.ToString());
                }
                else
                {
                    // Receive incoming message and try to concatenate all parts
                    if (data.Concatenation != null)
                    {
                        _messageComposer.AddMessage(data);

                        _log.Info("DeliverSm part received: Sequence: {0}, SourceAddress: {1}, Concatenation ( {2} )" +
                                  " Coding: {3}, Text: {4}",
                                  data.Header.Sequence, data.SourceAddress, data.Concatenation, data.DataCoding, _client.EncodingMapper.GetMessageText(data));
                    }
                    else
                    {
                        _log.Info("DeliverSm received : Sequence: {0}, SourceAddress: {1}, Coding: {2}, Text: {3}",
                                  data.Header.Sequence, data.SourceAddress, data.DataCoding, _client.EncodingMapper.GetMessageText(data));
                    }

                    // Check if an ESME acknowledgement is required
                    if (data.Acknowledgement != SMEAcknowledgement.NotRequested)
                    {
                        // You have to clarify with SMSC support what kind of information they request in ESME acknowledgement.

                        string messageText = data.GetMessageText(_client.EncodingMapper);

                        var smBuilder = SMS.ForSubmit()
                                        .From(data.DestinationAddress)
                                        .To(data.SourceAddress)
                                        .Coding(data.DataCoding)
                                        .ConcatenationInUDH(_client.SequenceGenerator.NextReferenceNumber())
                                        .Set(m => m.MessageType = MessageTypes.SMEDeliveryAcknowledgement)
                                        .Text(new Receipt
                        {
                            DoneDate = DateTime.Now,
                            State    = MessageState.Delivered,
                            //  MessageId = data.Response.MessageId,
                            ErrorCode  = "0",
                            SubmitDate = DateTime.Now,
                            Text       = messageText.Substring(0, Math.Min(20, messageText.Length))
                        }.ToString()
                                              );



                        _client.Submit(smBuilder).ConfigureAwait(false);
                    }
                }
            }
            catch (Exception ex)
            {
                data.Response.Header.Status = CommandStatus.ESME_RX_T_APPN;
                _log.Error(ex, "Failed to process DeliverSm");
            }
        }
        private async Task SubmitSingleMessage()
        {
            DataCodings coding = GetDataCoding();



            var sourceAddress = new SmeAddress(tbSrcAdr.Text, (AddressTON)byte.Parse(tbSrcAdrTON.Text), (AddressNPI)byte.Parse(tbSrcAdrNPI.Text));

            var destinationAddress = new SmeAddress(tbDestAdr.Text, (AddressTON)byte.Parse(tbDestAdrTON.Text), (AddressNPI)byte.Parse(tbDestAdrNPI.Text));

            _log.Info("Submit message To: {0}. Text: {1}", tbDestAdr.Text, tbMessageText.Text);


            ISubmitSmBuilder builder = SMS.ForSubmit()
                                       .From(sourceAddress)
                                       .To(destinationAddress)
                                       .Coding(coding)
                                       .Text(tbMessageText.Text)
                                       //Or you can set data
                                       //.Data(HexStringToByteArray("024A3A6949A59194813D988151A004004D215D2690568698A22820C49A4106288A126A8A22C2A820C22820C2A82342AC30820C4984106288A12628A22C2A420800"))

                                       //Apply italic style for all text  (mobile device should support basic EMS)
                                       //.Set(delegate(SubmitSm sm)
                                       //         {
                                       //             sm.UserDataPdu.Headers.Add(
                                       //                 InformationElementIdentifiers.TextFormatting, new byte[] {0, 1, ToByte("00100011")});
                                       //         })

                                       // Set ValidityPeriod expired in 2 days
                                       .ExpireIn(TimeSpan.FromDays(2))

                                       //Request delivery receipt
                                       .DeliveryReceipt();
            //Add custom TLV parameter
            //.AddParameter(0x1403, "free")

            //Change SubmitSm sequence to your own number.
            //.Set(delegate(SubmitSm sm) { sm.Sequence = _client.SequenceGenerator.NextSequenceNumber();})

            SubmitMode mode = GetSubmitMode();

            switch (mode)
            {
            case SubmitMode.Payload:
                builder.MessageInPayload();
                break;

            case SubmitMode.ShortMessageWithSAR:
                builder.ConcatenationInSAR();
                break;
            }

            try
            {
                IList <SubmitSmResp> resp = await _client.Submit(builder);

                if (resp.All(x => x.Header.Status == CommandStatus.ESME_ROK))
                {
                    _log.Info("Submit succeeded. MessageIds: {0}", string.Join(",", resp.Select(x => x.MessageId)));
                }
                else
                {
                    _log.Warn("Submit failed. Status: {0}", string.Join(",", resp.Select(x => x.Header.Status.ToString())));
                }
            }
            catch (Exception ex)
            {
                _log.Error("Submit failed. Error: {0}", ex.Message);
            }

            // When you received success result, you can later query message status on SMSC
            // if (resp.Count > 0 && resp[0].Status == CommandStatus.ESME_ROK)
            // {
            //     _log.Info("QuerySm for message " + resp[0].MessageId);
            //     QuerySmResp qresp = _client.Query(resp[0].MessageId,
            //         srcTon, srcNpi,srcAdr);
            // }
        }