Tuesday 30 September 2014

How to send SMS/MMS with Twilio using python

Sending an SMS (Short Message Service) message via Twilio is really easy. You will need to look in your Twilio account to get the sid and authentication token as well as your twilio number. Once you have those three pieces of key information, you can send an SMS message.


you’ll need to sign up on Twilio(https://www.twilio.com/try-twilio/) and you’ll also need to install the Python twilio wrapper. To install the latter, just do the following:
 
pip install twilio

 
so you can send message by this site through your python programing code. Now after creating account take SID auth token number and twillio number, fill these in below code and run it.

 

Sending SMS only

from twilio.rest import TwilioRestClient
 
#----------------------------------------------------------------------
def send_sms(msg, to):
    """"""
    sid = "text-random"
    auth_token = "youAreAuthed"
    twilio_number = "123-456-7890"
 
    client = TwilioRestClient(sid, auth_token)
 
    message = client.messages.create(body=msg,
                                     from_=twilio_number,
                                     to=to,
                                     )
if __name__ == "__main__":
    msg = "Hello from Python!"
    to = "111-111-1111"
    send_sms(msg, to)

Sending an MMS Message

import configobj
from twilio.rest import TwilioRestClient

#----------------------------------------------------------------------
def send_mms(msg, to, img):
    """"""
    cfg = configobj.ConfigObj("/path/to/config.ini")
    sid = cfg["twilio"]["sid"]
    auth_token = cfg["twilio"]["auth_token"]
    twilio_number = cfg["twilio"]["twilio_number"]

    client = TwilioRestClient(sid, auth_token)

    message = client.messages.create(body=msg,
                                     from_=twilio_number,
                                     to=to,
                                     MediaUrl=img
                                     )

if __name__ == "__main__":
    msg = "Hello from Python!"
    to = "111-111-1111"
    img = "http://www.website.com/example.jpg"
    send_mms(msg, to=to, img=img)




 

Thanks guys for your support.

No comments:

Post a Comment