# How to Get Started with Azure Communication Services Part 2 of 2 - Send SMS messages

# SMS is universal

Almost every phone in the world can send and receive SMS messages. It is a universal message format that many companies use to inform customers or to start customer workflows, like multi-factor authentication. Sending and receiving SMS messages from applications can be hard and involves setting up and managing complex infrastructure. Azure Communication Services (opens new window) makes sending and receiving SMS messages easy, without you having to manage any infrastructure.

This post is part of a series of posts in which we create an application that enables you to chat and send SMS messages:

  1. How to Get Started with Azure Communication Services Part 1 of 2 - Create a chat app (opens new window)
  2. How to Get Started with Azure Communication Services Part 2 of 2 - Send SMS messages (opens new window) (this post)

In this second post, we'll add to the chat application that we've built in part 1 and make it so that it can send SMS messages through Azure Communication Services.

# Prerequisites

If you want to follow along, you'll need the following:

# Send and receive SMS messages

To use the SMS feature of Azure Communication Services, we need a phone number, which we can provision in Azure Communication Services.

  1. Go to the Azure portal (opens new window)
  2. Navigate to the Azure Communication Services resource
  3. Select the Phone numbers menu
  4. Select Get
  5. For Use Case, select "An application will be making calls or sending SMS messages"
  6. Next, select a Toll-free number
  7. For SMS, select Outbound SMS as we will send SMS messages and not receive them
  8. Select Next: Numbers to go to the next step

(Get a phone number in the Azure portal)

  1. Here, you can select an area code and how many numbers you want. Leave the default settings and select Search. This will find a phone number for you
  2. Select Next: Summary and Place order to get the phone number

(select a phone number area code in the Azure portal)

Now that we have a phone number, we can implement SMS in our ASP.NET Core application.

First, open the application in Visual Studio or VS Code and add the following NuGet package:

  • Azure.Communication.SMS

(NuGet package to add in Visual Studio)

Next, add two files called SMSService.cs and ISMSService.cs. Make sure that the SMSService.cs file contains the following code:

SMSService.cs:

    public class SMSService : ISMSService
    {
        private SmsClient _smsClient;
        private string _communicationServicePhoneNumber;
        public SMSService(string communicationServiceConnectionString, string communicationServicePhoneNumber)
        {
            _smsClient = new SmsClient(communicationServiceConnectionString);
            _communicationServicePhoneNumber = communicationServicePhoneNumber;
        }

        public void SendSMSMessage(string destinationPhoneNumber)
        {
          var response=  _smsClient.Send(
                from: new PhoneNumber(_communicationServicePhoneNumber),
                to: new PhoneNumber(destinationPhoneNumber),
                message: "Hello World via SMS");          
        }
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

The SMSService creates a new SmsClient instance with the Communication Services connection string and uses that to send an SMS message with.

And here is the code for the ISMSService.cs interface code:

    public interface ISMSService
    {
        void SendSMSMessage(string destinationPhoneNumber);
    }
1
2
3
4

In the ConfigureServices method of the Startup.cs class, we inject the SMSService and feed it the Communication Services connection string and also the phone number that we've created earlier and we put in the appsettings.json file.

Startup.cs ConfigureServices:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<IAccessTokenService>(s => new AccessTokenService(Configuration.GetConnectionString("CommunicationServiceConnection")));
            services.AddTransient<ISMSService>(s => new SMSService(Configuration.GetConnectionString("CommunicationServiceConnection"), Configuration.GetConnectionString("PhoneNumber")));
            services.AddSingleton<IChatService>(s => new ChatService(Configuration.GetValue<string>("CommunicationServiceEndpoint"), 
                new AccessTokenService(Configuration.GetConnectionString("CommunicationServiceConnection")),
                new SMSService(Configuration.GetConnectionString("CommunicationServiceConnection"), Configuration.GetValue<string>("PhoneNumber"))));
            
            services.AddControllersWithViews();
        }
1
2
3
4
5
6
7
8
9
10

appSettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "CommunicationServiceEndpoint": "Fill in your Azure Communication Service endpoint",
  "ConnectionStrings": {
    "CommunicationServiceConnection": "Fill in your Azure Communication Service connection string"
  },
  "PhoneNumber": "+18335837100"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Make sure that the phone number follows the E.164 format (opens new window).

Next, we use the SMSService in the ChatService. In the GetMessages method of ChatService.cs, we call the SendSMSMessage method of the SMSService to send an SMS when the user inputted a valid phone number in the chat window.

ChatService.cs:

    public class ChatService : IChatService
    {
        private ChatThreadClient chatThreadClient;
        private IAccessTokenService _tokenService;
        private ISMSService _smsService;
        public ChatService(string communicationServiceEndpoint, IAccessTokenService tokenService, ISMSService smsService)
        {
            _tokenService = tokenService;
            _smsService = smsService;

            // Your unique Azure Communication service endpoint
            Uri endpoint = new Uri(communicationServiceEndpoint);

            var user = _tokenService.CreateNewUser();

            //get user access token
            string userAccessToken = _tokenService.IssueUserAccessToken(CommunicationTokenScope.Chat, user);

            CommunicationUserCredential communicationUserCredential = new CommunicationUserCredential(userAccessToken);
            ChatClient chatClient = new ChatClient(endpoint, communicationUserCredential);

            var chatThreadMember = new ChatThreadMember(user)
            {
                DisplayName = "System user"
            };

            chatThreadClient = chatClient.CreateChatThread(topic: "Customer Service", members: new[] { chatThreadMember });
            SendMessage("Hi! Please type in your phone number to get help", "System user");
        }

        public void JoinChat()
        {
            var chatThreadMember = new ChatThreadMember(_tokenService.CreateNewUser())
            {
                DisplayName = "New user"
            };
            chatThreadClient.AddMembers(members: new[] { chatThreadMember });
        }

        public void SendMessage(string content, string displayName)
        {
            chatThreadClient.SendMessage(content, senderDisplayName: displayName);
        }

        public async Task<AsyncPageable<ChatMessage>> GetMessages()
        {
            var latestMessage = chatThreadClient.GetMessages().First();
            
                if (latestMessage.Type == "Text" && latestMessage.SenderDisplayName != "System user")
            {
                if (!Regex.IsMatch(latestMessage.Content, "(^^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\\s\\./0-9]*$)"))
                {
                    SendMessage("Please provide a valid phonenumber", "System user");
                }
                else
                {
                    _smsService.SendSMSMessage(latestMessage.Content);
                    SendMessage("Thank you! Please check your phone for further instructions", "System user");
                }
            }

            return chatThreadClient.GetMessagesAsync();
        }
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

Let's run the app to see what happens. When the application starts, it asks for a valid phone number. Give it a valid phone number, again using the E.164 format. You'll receive an SMS message that reads "Hello World via SMS".

(SMS message received from the application)

# Conclusion

Creating an application that uses Azure Communication Services (opens new window) is easy and straightforward. You can use the SDKs (opens new window) to talk to Communication Services and use chat (opens new window), SMS (opens new window), voice and video (opens new window) or telephone (opens new window) to communicate. Go and check it out!