Forwarding SMS Messages to Email Using Python

    Overview

    Businesses get communications through many channels. It can be handy to have a searchable archive of messages in one place. Forwarding SMS messages to email lets you keep both kinds of messages in one spot. Plivo makes it easy to forward SMS messages to email using the most popular web development languages. Here we walk through the process with .NET.

    Prerequisites

    • Plivo account: Sign up for a Plivo account if you don’t have one already.

    • Plivo phone number: To receive SMS, you must have a Plivo phone number that supports SMS. You can purchase numbers from the Numbers page of the Plivo console or by using the Numbers API.

      Buy a New Plivo Number

    The code example below presumes you have a Gmail account, but it’s easy to edit the code to support another SMTP client.

    Install Python and other modules

    You must set up and install Python and other modules to Forward Incoming SMS to Email. Here’s how.

    Install Python

    Operating SystemInstructions
    macOS & LinuxTo see if you already have Python installed, run the command python --version in the terminal
    WindowsTo install Python on Windows follow the instructions listed here.

    Create Project

    • Create a project directory, run the following command:

      $ mkdir mypythonapp
      
    • Change the directory to our project directory in the command line:

      $ cd mypythonapp
      

    Install modules

    • Install the packages using pip

      pip install secure-smtplib
      pip install flask
      

    We recommend that you use virtualenv to manage and segregate your Python environments, instead of using sudo with your commands and overwriting dependencies.

    Forward SMS to Email

    Create a file (we called ours email.py) and paste into it this code.

    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
    
    from flask import Flask, request
    import smtplib
    
    app = Flask(__name__)
    
    @app.route("/email_sms/", methods =['GET','POST'])
    def receive_sms():
        # Sender's phone number
        from_number = request.values.get('From')
        # Receiver's phone number - Plivo number
        to_number = request.values.get('To')
        # The text which was received on your Plivo number
        text = request.values.get('Text')
    
        # Print the message
        print('Message received from %s: %s' % (from_number, text))
        # Send the received SMS to your mail account
        return to_email(text, from_number)
    
    def to_email(text, from_number):
        user_name = '<email_address>'
        password = '<password>'
        from_ = '<from_email_addres>'
        to = ['<recipient_email_address>'] # must be a list
        subject = "SMS from %s" % (from_number)
        body = text
    
        # Prepare actual message
        message = """\From: %s\nTo: %s\nSubject: %s\n\n%s""" % (from_, ", ".join(from_), subject, body)
        try:
            server = smtplib.SMTP("smtp.gmail.com", 587)
            server.ehlo()
            server.starttls()
            server.login(user_name, password)
            server.sendmail(from_, to, message)
            server.close()
            print('successfully sent the email')
        except:
            print('failed to send email')
        return 'SMS sent to email'
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', debug=True)
    

    To run this file on the server, go to the folder where the file resides and use the command

    python number_masking.py
    

    You should see your basic server app in action on http://localhost:5000/email_sms/

    Note: If you use Gmail to send email, you'll have to use an app password, which will be treated as your password to send email from the app.

    Expose your local server to the internet

    To receive Incoming Messages and to handle callbacks, your local server should be able to connect with Plivo API service, Ngrok is a tunneling software used to expose a web server running on your local machine to the internet. Using Ngrok you can set webhooks which can talk to Plivo server.

    ngrok block diagram

    Install ngrok and run it on the command line, specifying the port that hosts the application on which you want to receive messages (5000 in this case):

    $ ./ngrok http 5000
    

    Ngrok will display a forwarding link that you can use as a webhook to access your local server over the public network.

    Sample ngrok CLI

    Create an Application

    1. Create a Plivo application by visiting Messaging > Applications and clicking on Add New Application, or by using Plivo’s Application API.
    2. Give your application a name — we called our Email SMS. Enter your server URL (for example https://61d8fb8f250c.ngrok.io/email_sms/) in the Message URL field and set the method as POST.
    3. Click on 'Create Application' to save your application.

    Create Application

    Assign a Plivo number to your app

    1. Navigate to the Numbers page and select the phone number you want to use for the application.
    2. Select XML Application from the Application Type drop-down list, and Email SMS (the name of the application) from the Plivo Application drop-down list.
    3. Click on 'Update Number' to save.

    Assign Application

    Test and validate

    Then send a text message to the Plivo number you associated with the application using a regular mobile phone.The incoming message should be reflected in your email.