Send a text message using .net

Sometimes, we want to send text messages from our application.  Whether it’s for sending out a secret code for two-tiered authentication, or sending out messages to subscribed members, it’s a feature that is occasionally needed, and one that I’ve recently needed.  There are many services out there that charge a fee, either monthly or per message, but the services are out there.  I’ve also seen several open-source applications that act as an instant messaging type service, in that they have a GUI and do not provide an API.  What I was unable to find was an API that handled all carriers, and was free.  So I built one, and here is how to use it.

Your first step is to download the single DLL, which is needed to use the API.  It’s open source, so you can get the code and make any changes you want and compile the DLL yourself, if you so desire.  You can get the DLL here, and the code here.

After adding the DLL as a reference to your project, it’s actually quite simple to use.  First, add the appropriate using:

using SMSOverEmail;

After the using statement is added, we are ready to start using the API.  The first step is to instantiate a new SMSOverEmail object.

SMSOverEmail.SMSOverEmail sms = new SMSOverEmail.SMSOverEmail

With our object instantiated, we need to set up the “From” part of our text message.  We are using SMTP to send the actual text message, so this is similar to setting up a SMTP client.

sms.EnableSsl = true;
sms.SMTPUserName = "userName@gmail.com";
sms.SMTPPassword = "password";
sms.Host = "smtp.gmail.com";
sms.Port = 587;
sms.From = new System.Net.Mail.MailAddress("userName@gmail.com");

These settings are correct if you are using Gmail, but you can use any email provider you wish, as long as you know the settings Smile

Once the “From” part is set up, we can set up the “To” part.  This is a text message, so we are delivering to a mobile device.  So, for the purpose of this API, you just need to know the 10 digit phone number, and the carrier it belongs to.  The API does the rest.

sms.PhoneNumber = "2345678901"; //a ten digit phone number
sms.RecipientCarrier = Carrier.SprintPCS;

The phone number is a string, and must be the 10 digit phone number belonging to the phone.  The Carrier enumerator has over 60 carriers to choose from.  In our example, we are sending a text message to (234)567-8901 which is held by a Sprint customer.

Now that the recipient and the sender are setup, we can send our text message.

sms.SendTextMessage("test message");

The SendTextMessage function has many different overloads, they are all documented inline, but you can see the full list on the projects CodePlex documentation page.

No tutorial would be complete without showing all of the code put together in a complete console application:

namespace SSMSTest
{
    using System;
    using SMSOverEmail;

    class Program
    {
        static void Main(string[] args)
        {
            SMSOverEmail.SMSOverEmail sms = new SMSOverEmail.SMSOverEmail();
            sms.EnableSsl = true;
            sms.SMTPUserName = "userName@gmail.com";
            sms.SMTPPassword = "password";
            sms.Host = "smtp.gmail.com";
            sms.Port = 587;
            sms.From = new System.Net.Mail.MailAddress("userName@gmail.com");

            sms.PhoneNumber = "2345678901"; //a ten digit phone number
            sms.RecipientCarrier = Carrier.SprintPCS;

            sms.SendTextMessage("test message");
        }
    }
}

The API also comes with a dictionary containing the actual carrier name, along with the enumerator.  For example, Carrier.ATT is AT&T.  Each enumerator is simple to understand, but I threw it in in case you needed a user-friendly list of carriers.  Assuming sms is the name of your SMSOverEmail object, then sms.CarrierNames is the dictionary.  It’s in the form of Dictionary, where Carrier is the enumerator, and string is the user-friendly name.

As always, I would love to hear from you.  Please leave your thoughts about this post below, especially if this post has helped you Smile  If you have any questions, I’ll be sure to do my best to answer those as well.

Remove Recipients From Email When Not In Release Mode

Often, we need our applications to send emails to people.  When this is the case, if we are not careful, we can end up sending test emails to our external users.  We can get around this very easily by using preprocessor directives and writing our own SmtpClient class.

This isn’t a tutorial on sending email through .net, but here is a very basic function that will do that.  First the usings:

using System.Collections.Generic;
using System.Net.Mail;

Then the function:

public void sendEmail(string message, string subject, MailAddress fromAddress, 
            List<MailAddress> toAddressList, List<MailAddress> ccAddressList, 
            List<MailAddress> bccAddressList)
{
    MailMessage mail = new MailMessage();
    SmtpClient client = new SmtpClient();

    mail.From = fromAddress;
    mail.Subject = subject;
    mail.Body = message;

    foreach (MailAddress address in toAddressList)
    {
        mail.To.Add(address);
    }

    foreach (MailAddress address in ccAddressList)
    {
        mail.CC.Add(address);
    }

    foreach (MailAddress address in bccAddressList)
    {
        mail.Bcc.Add(address);
    }

    client.Host = "smtp.gmail.com";
    client.Port = 587;
    client.Credentials = new System.Net.NetworkCredential("username", "****");
    client.EnableSsl = true;

    client.Send(mail);
}

Now, that is just a generic function that will send an email.  I’m not going to bother explaining it.  See that last line though: “client.Send(mail);”?  That Send function is what we want to change.  To do that, we create a new class, with SmtpClient as the base, and then overload the Send function.

Our usings are the same:

using System.Collections.Generic;
using System.Net.Mail;

And here is our new class:

class NewSmtpClient : SmtpClient
{
    public void Send(MailMessage message)
    {
#if DEBUG
        List<MailAddress> toList = new List<MailAddress>(message.To);
        List<MailAddress> ccList = new List<MailAddress>(message.CC);
        List<MailAddress> bccList = new List<MailAddress>(message.Bcc);

        foreach(MailAddress address in toList)
        {
            if(address.Host.ToLower() != "gmail.com")
            {
                message.To.Remove(address);
            }
        }

        foreach (MailAddress address in ccList)
        {
            if (address.Host.ToLower() != "gmail.com")
            {
                message.CC.Remove(address);
            }
        }

        foreach (MailAddress address in bccList)
        {
            if (address.Host.ToLower() != "gmail.com")
            {
                message.Bcc.Remove(address);
            }
        }
#endif

        //there must be at least one recipient 
        if ((message.To.Count + message.CC.Count + message.Bcc.Count) > 0)
        {
            base.Send(message);
        }
    }
}

Of course, now that we have our new class, we need to change our calling function.  So, in our generic function we will change

SmtpClient client = new SmtpClient();

to

NewSmtpClient client = new NewSmtpClient();

So, I want to explain a few things here.  See that fifth line, #if DEBUG?  That’s a preprocessor directive.  Visual Basic has them to, but MSDN just called them directives.  Anyway, these directives are processed before the compiler runs.  Anything between #if DEBUG and #endif will not even show up in the IL Code if you compile in Release mode.

What is happening in our example class here, is that when you call client.Send(mail), if you are in DEBUG mode, then we remove any email recipient whose host is not “gmail.com”.  Of course, you would use any host that you want.  This results in a recipient list that is any of the original recipients but, no emails will be sent to “gmail.com”.  I don’t think that is worded very well, so let me visualize it for you.

  • To List
    • one@gmail.com
    • one@yahoo.com
    • one@bing.com
  • CC List
    • two@gmail.com
    • two@yahoo.com
    • two@bing.com
  • BCC List
    • three@gmail.com
    • three@yahoo.com
    • three@bing.com

After we call Send, but before the email is actually sent, the new recipient list looks like this:

  • To List
    • one@gmail.com
  • CC List
    • two@gmail.com
  • BCC List
    • three@gmail.com

The if statement at the end is because it is possible that we will end up removing all of our recipients, in which case we don’t want to send the email.  In this scenario, but without such an if statement, an exception will be thrown.

If this post has helped you in any way, please leave a comment below. Or, if you solved this method another way, please leave a comment.  I would like to hear from you!