Forwarding SMS Messages to Email Using Python

    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 Python.

    Prerequisites

    To get started, you need a Plivo account — sign up with your work email address if you don’t have one already. To receive incoming messages, you must have a Plivo phone number that supports SMS; you can rent numbers from the Numbers page of the Plivo console or by using the Numbers API. If this is your first time using Plivo APIs, follow our instructions to set up a Python development environment.

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

    Create the forward SMS application

    Create a file called smsemail.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
        to_number = request.values.get('To')
        # The text that 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_address>'
        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 email')
        except:
            print('failed to send email')
        return 'SMS sent to email'
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', debug=True)
    

    Save the file and run it.

    python smsemail.py
    
    Note: If you use Gmail to send email, you must use an app password, which will be treated as your password to send email from the application.

    You should see your basic server application in action at http://localhost:5000/email_sms/.

    Set up ngrok to expose your local server to the internet.

    Create a Plivo application

    Associate the controller you created with Plivo by creating a Plivo application. Visit Messaging > Applications and click Add New Application. You can also use Plivo’s Application API.

    Give your application a name — we called ours Email SMS. Enter the server URL you want to use (for example https://<yourdomain>.com/email_sms/) in the Message URL field and set the method to POST. Click Create Application to save your application.

    Create Application

    Assign a Plivo number to your application

    Navigate to the Numbers page and select the phone number you want to use for this application.

    From the Application Type drop-down, select XML Application.

    From the Plivo Application drop-down, select Email SMS (the name we gave the application).

    Click Update Number to save.

    Assign Application

    Test

    Send a text message to the Plivo number you associated with the application using a regular mobile phone. The incoming message should be forwarded to the email address you specified.