Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking email with Python

Tags:

python

email

People also ask

Can Python automate email?

Automate it with Python! In this guide, I'll show you how to automate sending emails with Python. We'll be using Gmail in this tutorial, so make sure you have a Gmail account to test out this automation. If you don't feel like reading, you can watch my video instead!

How do I connect Python to email?

Set up a secure connection using SMTP_SSL() and . starttls() Use Python's built-in smtplib library to send basic emails. Send emails with HTML content and attachments using the email package.


Gmail provides the ability to connect over POP, which you can turn on in the gmail settings panel. Python can make connections over POP pretty easily:

import poplib
from email import parser

pop_conn = poplib.POP3_SSL('pop.gmail.com')
pop_conn.user('username')
pop_conn.pass_('password')
#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
#Parse message intom an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
    print message['subject']
pop_conn.quit()

You would just need to run this script as a cron job. Not sure what platform you're on so YMMV as to how that's done.


Gmail provides an atom feed for new email messages. You should be able to monitor this by authenticating with py cURL (or some other net library) and pulling down the feed. Making a GET request for each new message should mark it as read, so you won't have to keep track of which emails you've read.


While not Python-specific, I've always loved procmail wherever I could install it...!

Just use as some of your action lines for conditions of your choice | pathtoyourscript (vertical bar AKA pipe followed by the script you want to execute in those cases) and your mail gets piped, under the conditions of your choice, to the script of your choice, for it to do whatever it wants -- hard to think of a more general approach to "trigger actions of your choice upon receipt of mails that meet your specific conditions!! Of course there are no limits to how many conditions you can check, how many action lines a single condition can trigger (just enclose all the action lines you want in { } braces), etc, etc.


People seem to be pumped up about Lamson:

https://github.com/zedshaw/lamson

It's an SMTP server written entirely in Python. I'm sure you could leverage that to do everything you need - just forward the gmail messages to that SMTP server and then do what you will.

However, I think it's probably easiest to do the ATOM feed recommendation above.

EDIT: Lamson has been abandoned


I found a pretty good snippet when I wanted to do this same thing (and the example uses gmail). Also check out the google search results on this.