Created
May 1, 2017 20:52
-
-
Save mattmakai/690117947874753a01d881060689125e to your computer and use it in GitHub Desktop.
Send a Twilio SMS using Python 3.6 stdlib
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import base64 | |
import json | |
import os | |
import urllib | |
from urllib import request, parse | |
TWILIO_SMS_URL = "https://api.twilio.com/2010-04-01/Accounts/{}/Messages.json" | |
def lambda_handler(event, context): | |
twilio_account_sid = os.environ.get("TWILIO_ACCOUNT_SID") | |
twilio_auth_token = os.environ.get("TWILIO_AUTH_TOKEN") | |
to_number = event['To'] | |
from_number = event['From'] | |
body = event['Body'] | |
if not twilio_account_sid: | |
return "Unable to access Twilio Account SID." | |
elif not twilio_auth_token: | |
return "Unable to access Twilio Auth Token." | |
elif not to_number: | |
return "The function needs a 'To' number in the format +12023351493" | |
elif not from_number: | |
return "The function needs a 'From' number in the format +12023351493" | |
elif not body: | |
return "The function needs a 'Body' message to send." | |
print(twilio_account_sid) | |
print(twilio_auth_token) | |
print(to_number) | |
print(from_number) | |
print(body) | |
# insert Twilio Account SID into the REST API URL | |
populated_url = TWILIO_SMS_URL.format(twilio_account_sid) | |
post_params = {"To": to_number, "From": from_number, "Body": body} | |
# encode the parameters for Python's urllib | |
data = parse.urlencode(post_params).encode() | |
req = request.Request(populated_url) | |
# add authentication header to request based on Account SID + Auth Token | |
authentication = "{}:{}".format(twilio_account_sid, twilio_auth_token) | |
base64string = base64.b64encode(authentication.encode('utf-8')) | |
req.add_header("Authorization", "Basic %s" % base64string.decode('ascii')) | |
try: | |
# perform HTTP POST request | |
print(data) | |
print(req.headers) | |
with request.urlopen(req, data) as f: | |
print(f.read().decode('utf-8')) | |
except Exception as e: | |
# something went wrong! | |
print(e) | |
return e |
@life-efficient in the US and Canada you add the media_url
parameter with the same code. however, it won't work outside US/Canada instead it will send a URL of a page that contains the image https://www.twilio.com/docs/sms/tutorials/how-to-send-sms-messages-python
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How could we adapt this to send MMS?