DEV Community

Cover image for Sending SMS with Transmitly (C#)
Jeremy
Jeremy

Posted on • Originally published at Medium

Sending SMS with Transmitly (C#)

Whether you’re confirming an order, resetting a password, or sending an account notification, SMS messages are key to ensuring a great user experience. However, managing these SMS messages effectively can get complex, fast. That’s where Transmitly comes in — a solution designed to streamline and enhance your SMS message process. In this article, you’ll explore how Transmitly, with its powerful features, can revolutionize the way you handle SMS communications.

What is a transactional communication?

Transactional communications are sent in response to specific actions or events within your application or service. Unlike marketing communications, which are typically sent in bulk to promote products or services, transactional communications are integral parts of your business operations. Common examples include:

  • Order confirmations
  • Password reset requests
  • Account notifications
  • One time password (OTP)
  • Appointment reminders

What is Transmitly?

Transmitly is a robust platform for managing and controlling outgoing transactional communications, including emails, SMS, and push notifications. It centralizes your communication management, offers flexible configuration, and simplifies message composition. Whether you’re a developer or running a business, Transmitly helps you streamline your communication processes. It supports multiple service providers and integrates easily with a variety of tools, making your communications more efficient and reliable.

Methods of Sending SMS

  • SMS Gateway: Strangely enough, some carriers support sending SMS messages via special email addresses. They are generally not very reliable and you must know which provider your recipient is using.
  • 3rd-Party Service Providers: Twilio, InfoBip, Plivo, and more

Without Transmitly

There’s quite a few options out there to choose from for SMS communications. There’s also a lot more restrictions to be allowed to send SMS with any service. We’ll assume you’ve made it through the hoops of getting setup and you’ve chosen Twilio.

Add the Twilio Api:

dotnet install Twilio
Enter fullscreen mode Exit fullscreen mode
// Install the C# / .NET helper library from twilio.com/docs/csharp/install
using System;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using System.Threading.Tasks;

class SmsService {

    public static async Task OrderProcessed(string recipient) {

        // Find your Account SID and Auth Token at twilio.com/console
        // and set the environment variables. See http://twil.io/secure
        string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        TwilioClient.Init(accountSid, authToken);

        var message = await MessageResource.CreateAsync(
            body: "Your order is being processed, thanks!",
            from: new Twilio.Types.PhoneNumber("+15017122661"),
            to: new Twilio.Types.PhoneNumber(recipient));
        Console.WriteLine(message.Body);
    }
}
Enter fullscreen mode Exit fullscreen mode

(Example take from the Twilio quick start)

What’s Wrong with This Approach?

On the surface, not a lot. Twilio and their SDK will work great for a long time.

  • More work to be done: Not shown is just how to deserialize the API response and make sense of it in your application.
  • Vendor Lock: The more communications, the more you’re going to use their API. That doesn’t pose a problem until something changes with their service. Price increases, API changes, etc are all going to cost you and your application.

The Transmitly Way

First, you need to install the nuget package:

# Install the base Transmitly package
dotnet install Transmitly
# We'll need the MailKit Transmitly package to use SMTP
dotnet install Transmitly.ChannelProvider.Twilio
# To make our lives easier, we'll use the optional MS DI extensions 
dotnet install Transmitly.Microsoft.Extensions.DependencyInjection
Enter fullscreen mode Exit fullscreen mode

We need to do a little configuration first. In your Startup.cs

//All usual extensions and properties are located in this root namespace
using Transmitly;
...
//AddTransmitly comes from MS DI extensions library.
//Without the MS DI library, you can still wire up Transmitly using it's
//fluent builder.
services.AddTransmitly(tly=>{ 
  tly
  //AddTwilioSupport comes from the Twilio library
  //This allows us to setup what's needed in a strongly typed and central way
  .AddTwilioSupport(twilio =>
  {
      twilio.AuthToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");
      twilio.AccountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
  }
  .AddPipeline("OrderProcessing", pipeline=>
  {
    //AddSms is a core feature, a channel, of Transmitly
    //Out of the box there are Email, SMS, Voice and Push
    pipeline.AddSms(sms=>{
      //Transmitly is a bit different. All of our communication content is configured by using templates.
      //Out of the box, we have static or string templates, file and even embedded template support.
      //There are multiple types of templates to get you started. You can even create templates 
      //specific to certain cultures!
      sms.Body.AddStringTemplate("Your order is being processed, thanks!");
      //We've kept it simple for this example, but Transmitly also supports various template engines.
      //Adding a template engine can make your messages a bit more useful by showing the order# or user's name.
   });
})
Enter fullscreen mode Exit fullscreen mode

At first glance, it looks similar to the original code. You still have credentials and SMS content, but now everything is centralized. Configuration is placed in your Startup.cs, but as your system grows, you can easily move this into its own class library.

With Transmitly, you’re also creating a communications pipeline, which gives you centralized control over your communications. You can manage what messages are available and which channel providers are used to send them. In short, you now have a loosely coupled, centralized way of managing your communications.

Next, let’s modify our original sending code:

using Transmitly;

public class SmsService
{
  private readonly ICommunicationsClient _commsClient;

  public EmailService(ICommunicationsClient commsClient)
  {
    _commsClient = commsClient;
  }

  public async Task OrderProcessed(string recipient)
  {
    //Dispatch (send) the transactional sms to our recipient using our configured Twilio account and our "OrderProcessing" pipeline.
    var result = await communicationsClient.DispatchAsync("OrderProcessing", "+15017122661".AsAudienceAddress(), new { });

    if (response.IsSuccessful)
    {
        Console.WriteLine("Sms sent successfully!");
    }
    else
    {
        Console.WriteLine($"Failed to send SMS");
    }
}
Enter fullscreen mode Exit fullscreen mode

That’s all there is to it! The code may look similar, but these changes open up several new possibilities:

  • Change Channels: While today you might only need SMS, in the future, you might want to add email, push notifications or better yet, let users set their communication preferences. Transmitly lets you manage that easily with Pipelines, Channels, and Channel Providers.
  • Change Providers: If Twilio gives you issues, you can quickly switch to another provider, like Infobip by adding a new Transmitly library and updating your configuration.

You now have the power and flexibility to grow your communication strategy in a safe, controlled, and testable manner.

Key Benefits of Using Transmitly

  • Centralized Communication Management: Manage emails, SMS, and push notifications from one platform, reducing complexity and boosting efficiency.
  • Flexible Configuration: Switch between service providers like SendGrid or Infobip without altering your business logic.
  • Simplified Message Composition: Externalize message composition, making it easier to modify and manage your communication strategy.
  • Scalability and Reliability: Designed for high-volume communications with reliable performance.
  • Provider Agnostic: Integrates seamlessly with almost any communication service (e.g., Twilio, Infobip, SMTP). Easily extensible for adding any missing features you might need.

Conclusion

Transactional communications are vital to modern applications, ensuring timely and effective communication with users. Transmitly offers a powerful alternative that simplifies the process, improves deliverability, and provides valuable insights. By integrating Transmitly into your app, you can ensure your transactional communications are sent efficiently and reliably, enhancing user experience and engagement.

Peaked your interest? Check out the Transmitly Github Repo for more exciting ways to manage your business' communications strategies.

Top comments (0)