How to send emails from Gmail with Python in case of Exception


Lately I’m discovering Python, it’s an incredible programming language, you can do pretty much what you want!

For example, I’m using a bot for Instagram written in python and I’m running it on a remote server.

The problem is that this script occasionally gets stuck, and the only way to find out why was connect with ssh to the server and control the situation.

So I said to myself: why not auto-send me an email if the script crashes?

Said, done.

Code: send emails with python

It did not even amaze me that python did not even need to install external libraries in order to do it.

If, as in my case, you want to send emails from your gmail account, this is what you need to do:

  • First: You need to enable access to less secure apps from your Google Account settings.
  • Second: here is the code:
import smtplib
server = smtplib.SMTP('', 587)
msg = "MESSAGE"
server.sendmail("EMAIL_ADDRESS", "EMAIL_ADDRESS", msg)

and … Your email is sent!

This was my first attempt, but I realized that I wanted more.

For an aesthetic (but also practical) reason, it was better to show a custom name in the sender field, instead of my gmail address. (For example “Instagram script chrashed!”)
Secondly, I wanted the exception in the body of the mail, so that you know what happened.
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

    #here goes your script

except Exception as e:
    s = str(e)
    fromaddr = "EMAIL_ADDRESS"
    toaddr = "EMAIL_ADDRESS"
    msg = MIMEMultipart()
    msg['From'] = "CUSTOM_SENDER_NAME"
    msg['To'] = toaddr
    msg['Subject'] = "CUSTOM_SUBJECT"

    body = "MESSAGE" + str(e)
    msg.attach(MIMEText(body, 'plain'))

    server = smtplib.SMTP('', 587)
    server.login(fromaddr, "EMAIL_PASSWORD")

    text = msg.as_string()
    server.sendmail(fromaddr, toaddr, text)

The end!

Python is really cool.

Then you can go further, you can send mail a bit more nice, with more formatting, with attachments, etc.

Once you understand the basic mechanism, add all the frills you want is really easy, and python documentation, as well as Stackoverflow, can help you as always.