Python – How to send a text message.

How to send a text message (SMS) to a smart phone.
March 22, 2019

So, you are working on a project that needs to send a text message to one or more smart phones. Maybe your working on something that will send out a message if an important printer runs out of paper, or the companies file server runs out of free space, or someone leaves the back door of the warehouse open again. OK, so how does one send a text message using python?

Python – How to send a text message.

How to send a text message (SMS) to a smart phone.
March 22, 2019

So, you are working on a project that needs to send a text message to one or more smart phones. Maybe your working on something that will send out a message if an important printer runs out of paper, or the companies file server runs out of free space, or someone leaves the back door of the warehouse open again. OK, so how does one send a text message using python?

Text messaging, also commonly called 'Instant Messaging' or simply 'SMS messaging', is a way to send a short text to the 'Instant Messaging' app on a smart phone.

Note: In this blog post, I'm using the words 'mobile device', 'cellphone', and 'smart-phone' to all mean the same thing; that tinny computer that we all carry around in our pockets.

Here is the bit of information that's the key to solve this:

Every mobile device (smart phone) that has it's own phone number, also has a special EMAIL address that can be used to send it a text (instant) message. And python is very good about sending emails. So if we can figure out what that special email address is, we can used it to send the message.

How does this work.

When you send a message to the phone's special SMS email address, your message will go from your workstation, to an email server. This works the same way as it would to send an email to anyone else in the world.

From the email server, your message then flows to something called an SMS gateway. These SMS gateways are Internet servers, usually owned by the cellphone service provider, that pass text messages to and from mobile devices. The domain name (the part of the email address that comes after the '@' character) is the pointer to the SMS gateway.

And finally, your message flows from the SMS gateway, to the mobile device, as an text message.

The whole trip, from workstation to phone, takes about 3 minutes (depending on Internet traffic of course).

Also, messages can flow the other way; you can send an SMS message from the instant messaging app on a phone, to someone's email address, and it will arrive in their inbox in about 3 minutes.

Finding the SMS address of the Smart Phone(s).

Technique Number 1:
By far the easiest way to find the special SMS email address of a phone, is to ask your client to text you their name, using the Instant Messaging application on their smart phone. But on the line where they would normally enter the phone number to send it to, have them enter your email address (like to Joe@GSW7.net). Wait a few minutes, and then check your inbox. You should see an email from a strange address like 3334445555@PhoneCarrier.com, with their name in the body of the email. That strange address is their SMS email address. Easy.

Technique Number 2:
Almost every smart phone in the United States is on one of 12 cellphone service providers. If you know the phone number, and what service provider they are using, you can work out the email address.
Take a look at this blog post on the Digital Trends website to learn how:
https://www.digitaltrends.com/mobile/how-to-send-a-text-from-your-email-account

Technique Number 3:
So what if you only have the phone number, but don't know who the service provider is? Using the info in the Digital Trends posting (above), create a list of addresses that might be the correct one. The list will be short. Send a test email to each of these addresses. You will get back many replies saying 'Undeliverable', or 'Unknown Address'.
Which of the test emails didn't give you an error reply?
BINGO..You have found the correct one!
This is the 'shotgun' method of finding the address. You shoot everything until you hit the right one.

Keeping track of the addresses.

Find the SMS email address for each of the mobile devices you may need to send to. I recommend that you keep this info in a spreadsheet, or in whatever application you are using for your contacts. And as always, be sure to BACK UP YOUR DATA!

Setting things up.

Now that we have one or more email address to send our message TO, we need the email info to send the message FROM.

Here is what you need to know.
1. the 'send from' email address (like JohnDoe@GMail.com),
2. the password for that email address,
3. and the name of your SMTP gateway (address of your email server).

What is SMTP?

The term 'SMTP' stands for 'Simple Mail Transfer Protocol'. It's a simple way to send an email message from your workstation, to your email server. One of the 'standard modules' (the pre-written code packages that you get automatically when you install python) is written for just this purpose. It is the smtplib module. So if your computer has python on it, it should already have this module. There is nothing special that needs to be downloaded for this project.

Finding your SMTP gateway (email server) address.

If you are using a free Gmail account as your 'send from' email address (like JoneDoe@Gmail.com), your SMTP gateway is 'smtp.gmail.com'. That is the SMTP address for all free Gmail accounts.

If you have your own website on an Internet Service Provider (like HostGator or FatCow), you can set up an email account using your cPanel portal. Your STMP gateway info will be in your settings window. You should be able to find on-line documentation on how to do this, or you can call the Customer Support number for assistances.

If your company has it's own email server, you can ask whoever is the admin of that server for an email account for your project. Be sure to ask about the SMTP gateway as well. If you can show that this is for 'company business', there should not be an issue.

For all other email providers, (like Hotmail, Verison, GoMail, etc..) you can do a Google search like 'HotMail SMTP' to find your SMTP address. This is all public information, you just have to go find it.

Summary and last bits of info:

IMPORTANT!
Some email providers set limits, like how many emails can be sent per hour, or how many people you can send a single email to. Be sure to check into this to insure that the email account you are using will meet your needs.

BEST PRACTICES
I have found that when sending emails from any automated processes (like a python script), that you should send the email to yourself, and send it to your clients as a blind copy. So that if one of your clients does a 'reply-all', only you will get the reply, and not everyone on the list. This will help prevent some very nasty email storms. Trust me on this one, I'm speaking from personnel experience here.
See my script (bellow) for an example of how to do this.
For more on this subject, do a web search for 'email storms'.

So, that pretty much all there is to it. I am including an example script (bellow). Please feel free to uses this script as you like.

Best of luck, to all my fellow geeks :)



import datetime
import smtplib

"""
SendATestMessage.py
Written by Joe Roten

This script demonstrates how to send a message to one or more smart-phones
   as an instant text message (SMS).
"""


def MSend(SendToList, Subject="", Message="", SendFrom="", SMTP="", Pwd="", BlindCopy=True):
    """Send a short message as an Email, or as a TextMessage (SMS)."""
    # Note: This function requires the 'smtplib' module.
    # Note: WriteToLog() which is used in this function, requires the datetime module.
    
    MText = []

    # State who the message is From.
    MText.append("From: " + SendFrom )

    # We want to send to the users as a 'blind carbon copy' (BCC).
    #   This will prevent any nasty 'reply-all' email storms.
    #   Trust me on this one; I speak from personal experience.
    #   For more info, do a web search for the words 'Email Storm'.
    # If you really want everyone to see the SendToList
    #   (and I highly advise against doing this),
    #   give BlindCopy the value False when you call this function.
    # The SendToList can be a Python LIST object, or a comma delimited string.
    #   The following code will convert either into a Python LIST.

    # State who we are sending the message To.
    try:
      if isinstance(SendToList, (list,)):
        send_to = SendToList
      else:
        send_to = SendToList.split(",")  
      send_to.append( SendFrom )
    except Exception as e:
      WriteToLog("ANSE0040", __file__, "MSend()", str(e) )
      WriteToLog("ANSW0043", __file__, "MSend()", "Assuming the SendTo address is the SendFrom address." )
      send_to = SendFrom 
    if BlindCopy:
      MText.append("To: " + SendFrom )
    else:
      MText.append("To: " + ", ".join(send_to) )

    # Next, we do the Subject line.
    MText.append("Subject: " + Subject)

    # Now, we add a blank line between the header and the Message.
    #   And then we add the Message.
    MText.append("")
    MText.append( Message )

    # Finally, an '.EndOfMessage' string to end it. 
    MText.append("\n.EndOfMessage\n")

    # OK, Send it.
    try:  
      server = smtplib.SMTP_SSL(SMTP, 465)
      server.ehlo()
      server.login(SendFrom, Pwd)
      server.sendmail(sent_from, send_to, "\n".join(MText) )
      server.close()      
    except Exception as e:
      # If something goes wrong, record it to the log file.
      WriteToLog("ANSE0040", __file__, "MSend()", str(e) )    
      

def WriteToLog( *args, filename="logfile.csv" ):
    """Record an event to the log file. This function uses the 'datetime' module."""
    result = datetime.datetime.utcnow().replace(microsecond=0).isoformat() + "z"
    for k in args:
        result = result + ', "' + str(k).strip() + '"'
    with open(filename, "a") as output:
        output.write (result + "\n")
    return result    


if __name__ == "__main__":

   # Define the 'send from' email account.
   SendFrom = "JohnDoe@Gmail.com"
   Pwd = "MyPasswordGoesHere"
   SMTP = "smtp.gmail.com"

   # Define who we are sending the message to.
   SendToList = []
   SendToList.append( "JamesSmith@BigBoss.com" ) # The Big Boss email.
   SendToList.append( "2063334444@CellphoneProvider.com" ) # Sue Max cell phone.
   SendToList.append( "2063334445@CellphoneProvider.com" ) # Mike James cell phone.

   # Define the message.
   Subject = "This is a test message sent by a python script."
   Message = "This is a test message sent by a python script."

   # Now send it.
   dummy = MSend(SendToList, Subject, Message, SendFrom, SMTP, Pwd)

Last updated: 2019-03-22


Written by Joe Roten

Computer tech, Graphic Artist, Photographer, Writer, Educator, Programmer, Jack of many trades, Social gadfly, and Scholar without portfolio. http://www.gsw7.net/joe/

Written by Joe Roten

http://www.gsw7.net/joe/

As always

The information on my website is FREE.
But donations to help pay for Coffee and Beer are always welcomed.
Thanks.