How to send emails from Gmail with Python in case of ExceptionPosts
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?
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('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login("EMAIL_ADDRESS", "EMAIL_PASSWORD") msg = "MESSAGE" server.sendmail("EMAIL_ADDRESS", "EMAIL_ADDRESS", msg) server.quit()
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 try: #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('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(fromaddr, "EMAIL_PASSWORD") text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit()
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.