Sending E-Mail or SMS/Text Messages Using GMail and Python

Thought I would share some Python code that I use when I want an alert via text message.  I originally used this in conjunction with a script to parse a web-page every minute and let me know when a particular Bitcoin miner was available.  Yes, they sold out that fast!

This is also terrific for IT-type alerts.  On my Ubuntu NAS, I have mdadm configured to call this script if there are any drive failures in my RAID.

It’s fully cross-platform and works in Windows, Mac, and Linux.  As long as you have Python installed, just edit a few lines and you have your own customizable alert system for just about anything your computer can communicate with.

# -*- coding: utf-8 -*-


Quickie walkthrough on sending an e-mail or SMS/text message
using GMail's SMTP server and Python.  This is 100% cross platform
and will work in Windows, Mac, Linux.

This code passes Pylint with a perfect 10.0 score.

Extensive list of SMS gateways:
Complete List of Email to SMS Gateways
Enjoy! ''' import smtplib def main(): ''' Send an e-mail or SMS text via GMail SMTP ''' gmail_username = '' # sender's gmail username gmail_password = 'password' # sender's gmail password smtp_server = '' smtp_port = 587 msg_from = '' # who the message is 'from' msg_subject = 'GMail SMTP to SMS' # message subject msg_to = 'phone_number@your_sms_gateway' # ex: msg_text = "I'm on a boat!" # If intent is SMS/text, remove/comment the header subject line # If intent is e-mail, add/uncomment the header subject line # A comment in python is a '#' symbol placed at the beginning of the line headers = ['From: {}'.format(msg_from), 'Subject: {}'.format(msg_subject), 'To: {}'.format(msg_to), 'MIME-Version: 1.0', 'Content-Type: text/html'] msg_body = '\r\n'.join(headers) + '\r\n\r\n' + msg_text session = smtplib.SMTP(smtp_server, smtp_port) session.ehlo() session.starttls() session.ehlo() session.login(gmail_username, gmail_password) session.sendmail(msg_from, msg_to, msg_body) session.quit() if __name__ == '__main__': main()


  1 comment for “Sending E-Mail or SMS/Text Messages Using GMail and Python

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.