How to Send an Automated Greeting Card with Twilio SMS

June 05, 2024
Written by
Reviewed by

How to send an Automated Greeting Card with Twilio SMS

Do you have any friends with birthdays coming up, or a holiday you don't want to forget? If you follow this tutorial, you can send a card to your friends and family and be sure it will arrive on time even if the event you want to remember is a month away. It will teach you how to send an automated text message with a greeting card motif.

Prerequisites

You’ll need a few things to follow along:

Buy a Twilio phone number

To complete this tutorial, you will need to buy a Twilio phone number. Log in to the Twilio Console , select Phone Numbers , and then click on the Buy a number button.

You will be on the Buy a Number page. If you’d like to request a number that is local to your region, you can enter your area code in the Number field. You can also choose any number you like that is available to buy.

Click the Search button to see what numbers are available. Select a number that you want, and be sure that SMS is checked in the Capabilities field of the number you choose. To get your new number, click Buy for the number you like from the results.

If you are in the United States, you need to complete a toll free or 10DLC (10-digit long code) verification process to be allowed to send automated text messages. Please view this help page for more information about the verification process.

Use automated SMS

To automate sending your text, you first need to create a messaging service. To begin configuration, go to your Twilio dashboard , click on Messaging, and then Services. Click on Create Messaging Service. You can give the service a friendly name, and choose “ notify my users” as the reason for use. In this example the service is called "Greeting."

Naming the message service with Greeting

In Step 2, you are asked to add senders. Select Phone Number as the sender type. Add the number you just bought from Twilio as your sender, by choosing it in the checklist in the menu. Step 3 is about Messaging Service Integration. This particular application won't do anything with incoming messages, so you can choose to ignore them by selecting the Drop the message option. In future applications, maybe you will want to do something with an incoming message.

The final page of service creation is about compliance info for your messaging service. If using a toll-free number, you can click  "complete setup" now, or you can "Skip setup" to handle compliance later. But know that you may have to complete the compliance step before you can send automated messages, depending on your location.

To write your code, you will create a .Net Console project in your IDE of choice. In Visual Studio Code, you can go to the command palette and choose to create a new .Net project, then create a Console project.

Following that, you can then add Twilio’s CLI by typing the following into your terminal:

dotnet add package Twilio

If you are in Visual Studio, you can use the built-in NuGet package manager to install the Twilio CLI instead of the command line.

Once the Twilio CLI is added, you will add the C# code to generate your automated message. Open up your program.cs file in your project. Replace the existing code with the following:

using System;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Microsoft.Extensions.Configuration;

class Program
{
   static void Main(string[] args)
   {
        var config = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddUserSecrets<Program>()
            .Build();


       string accountSid = config["Twilio:AccountSid"];
       string authToken = config["Twilio:AuthToken"];
       string twilioMessagingServiceSid = config["Twilio:MessagingSid"];

       TwilioClient.Init(accountSid, authToken);

       var timeToSend = new DateTime(2024,6,5,20,40,00);

       string dateString = timeToSend.ToString("MM/dd/yyyy HH:mm:ss");
       Console.WriteLine($"Sending a text on: {dateString}");

       var message = MessageResource.Create(
           body: "Greetings from Twilio!!",
           messagingServiceSid: twilioMessagingServiceSid,
           sendAt: timeToSend,
           to: new Twilio.Types.PhoneNumber("[YOUR_NUMBER_HERE]")
       );

       Console.WriteLine($"Sending using messaging SID: {message.Sid}");
   }
}

In the line var timeToSend = new DateTime(2024,6,5,20,40,00); you are setting the date and time that you want your automated card to be sent. This date (June 1), is just set as an example. For testing, you may want to set a time that's not too far out from the current time, before you activate your final application. Keep in mind that for automated SMS, you are limited to sending text messages in a time period between 15 minutes and 35 days from now. If your text message is queued to send too soon, your application will send an error message. The time that you set is also in the UTC timezone, so convert your time accordingly before sending.

In the line to: new Twilio.Types.PhoneNumber("[YOUR_NUMBER_HERE]"), replace the placeholder with the number of your intended recipient. For testing, this should be a phone number you have access to.

You will see some apparent mistakes in the above code, because you need to add a few more things to the project to secure your secrets. 

Enter the following lines of code into your terminal.

dotnet add package Microsoft.Extensions.Configuration
dotnet add package Microsoft.Extensions.Configuration.UserSecrets
dotnet user-secrets init

This will add the user secrets frameworks. This configures security on your application so that no API keys are visible in your code.

Now, get the security information from your Twilio account. The Account SID and the Auth Token are on your dashboard in the Account Info box. Look for the codes in the spaces as pictured below.

Where to find your Account SID, Auth Token, and sending Phone Number

For the messaging SID, you need to choose the Messaging SID associated with the service that you created. In the sidebar, choose Messaging, then Services and look for the Greeting service you created. The value for the SID will be shown here, as indicated by the yellow box in the screenshot below.

Showing the place to get the messaging service SID

Now, replacing the placeholder values with the security keys that you retrieved, enter the following lines of code into your console to secure your secrets.

dotnet user-secrets set Twilio:AccountSid [TWILIO_ACCOUNT_SID]
dotnet user-secrets set Twilio:AuthToken [TWILIO_AUTH_TOKEN]
dotnet user-secrets set Twilio:MessagingSid [TWILIO_MESSAGING_SID]

This code should no longer show errors and is ready to test.

Add an image

If you want to send out a simple message, you can scroll down to the Testing your Scheduled SMS section and see the results of your code. But, if you want to make this message a little more interesting for your recipient, you can add a graphic. A graphic can consist of any valid image type that is publicly accessible. You can choose an image you already have access to on the web, or you can use Twilio Assets to upload a new graphic to use. If you want to store your image using Twilio, you can upload Twilio Assets to the assets page under Functions and Assets.

Be aware that assets you upload will be publically available to anyone, so don't upload something into assets that you don't want to let other people see.

Click on messages on the left hand side and go to Assets (Classic). Click the plus sign in the upper left hand corner, and a dialog box will open that allows you to upload an image of your choice. Do not check the checkbox for "make private", as you want to be sure that your asset is visible from the internet, so that it can be sent with your SMS. 

Click the plus sign as shown to uploade
Example uploading an image

Now, you are going to alter the code, slightly, to add a few more lines to add an image to your message. The highlighted sections in the segment below show the code you will add to your project.

using System;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Microsoft.Extensions.Configuration;

class Program
{
   static void Main(string[] args)
   {
        var config = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddUserSecrets<Program>()
            .Build();

       string accountSid = config["Twilio:AccountSid"];
       string authToken = config["Twilio:AuthToken"];
       string twilioMessagingServiceSid = config["Twilio:MessagingSid"];

       TwilioClient.Init(accountSid, authToken);

       var timeToSend = new DateTime(2024,6,5,20,40,00);

       string dateString = timeToSend.ToString("MM/dd/yyyy HH:mm:ss");
       Console.WriteLine($"Sending a text on: {dateString}");

       var mediaUrl = new[]{
           new Uri("[URL_OF_Your_Asset]")
       }.ToList();

       var message = MessageResource.Create(
           body: "Greetings from Twilio!!",
           messagingServiceSid: twilioMessagingServiceSid,
           mediaUrl: mediaUrl,
           sendAt: timeToSend,
           to: new Twilio.Types.PhoneNumber("[YOUR_NUMBER_HERE]")
       );

       Console.WriteLine($"Sending using messaging SID: {message.Sid}");
   }
}

This new code allows you to add an image to your scheduled text. Replace the placeholder [URL_OF_Your_Asset] with the asset URL. If you are using an image from somewhere on the web, you can paste that URL here instead. If you are using an image uploaded to Twilio Assets, you will see the full URL of your image on the Assets (Classic) tab under Path.

Test your scheduled SMS

Run your program from the developer console. You will see the message "Sending a text on: [DATE]" and "Sending using messaging SID: [MessagingSID]" in your console if all the code has run correctly.

Now, you can see if your message is going to go out. Go to the Twilio Console and click on the Monitor tab. Then, click on Messaging. This will open the Programmable Messaging Logs tab where you can see your outgoing messages. Look for the Status column on the right hand side. It should show that a message is scheduled for the date and time you entered. 

If you want to test and see if a text message is going to arrive faster, you can use your own phone number as the recipient, and a shorter time interval to check. That time must be at least 15 minutes away from the time the program executes.

Once your text message is sent, you or your recipient will see the image, and text, at the time you selected, such as in this example.

 

Final result of text. It says "Happy birthday from Twilio" and shows a cake picture

Troubleshooting 

It can be difficult to test the automated SMS if you are trying to aim for a time that is too close or too far away. Remember, you can only set a time that's between 15 minutes and 35 days from now. A common error is to set a time that is too soon. You also need to remember to convert to the UTC time zone.

If you made a mistake and want to cancel your automated greeting, there is a solution. Go to your program and alter the messaging code to cancel the scheduled SMS. Then, run your code again. The following example shows the code for canceling an automated SMS. The critical code for the cancellation is highlighted.

using System;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Microsoft.Extensions.Configuration;

class Program
{
   static void Main(string[] args)
   {
       var config = new ConfigurationBuilder()
               .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
               .AddUserSecrets<Program>()
               .Build();

       string accountSid = config["Twilio:AccountSid"];
       string authToken = config["Twilio:AuthToken"];
       string twilioMessagingServiceSid = config["Twilio:MessagingSid"];

       TwilioClient.Init(accountSid, authToken);

       var message = MessageResource.Update(
           status: MessageResource.UpdateStatusEnum.Canceled,
           pathSid: "[MessagingPathSid]"
       );
    }
}

For the MessagingPathSid variable above, that is found on the Message Details page under Monitor > Logs > Messaging. Click on the date the message was queued, which is in the far left column, and it will bring up an information page showing details about the message. 

Please note that repeatedly scheduling and canceling a large number of messages could consume your account's scheduled message allocation. 

One final type of problem you may encounter relates to the image attached to your greeting. The image needs to be publicly accessible on the web. It also needs to be one of the accepted types, and a size of 5 MB or less. If your image cannot be sent, the SMS message will fail to send. Checking the logs as above, under Monitor > Logs > Messaging will show you details of a failed message. You can see more details about troubleshooting failed messages in our Help Center.

What's next to try?

If you want to send an automated call instead of a text, this C# tutorial will show you the way. The advantage of an automated voice call is that it doesn't require 10DLC verification for compliance, so you can send your message quickly.

If you want to learn more about message scheduling, check out the documentation for Messaging scheduling services. And, if you want to send an automated message with WhatsApp instead of SMS, Twilio also has you covered. This documentation explains how to automate a What'sApp message using an approved What'sApp template. 

Amanda Lange is a .NET Engineer of Technical Content. She is here to teach how to create great things using C# and .NET programming. She can be reached at amlange [at] twilio.com.