Skip to content

Instantly share code, notes, and snippets.

@jmahmood
Created June 8, 2011 08:52
Show Gist options
  • Save jmahmood/1014045 to your computer and use it in GitHub Desktop.
Save jmahmood/1014045 to your computer and use it in GitHub Desktop.
Retrieve Emails by Python, using Generators and Closures
# Jawaad Mahmood
# June 8th, 2011
# based on code I found at http://stackoverflow.com/questions/730573/django-to-send-and-receive-email.
# By using generators and nested functions / closures, I can more easily use this in code without screwing around
# with passing around messages, etc..
# Not sure if deletion works on the servers. Oh well :(
"""
# Example Usage
def fn(message):
print message.keys()
get_messages, close_server = __pop3()
all_messages = get_messages()
for message in all_messages:
fn(message)
close_server()
"""
from email.Parser import Parser
from email.Message import Message
import poplib
import imaplib
def imap_function_generator(
email_box_host="mail.example.com",
email_box_ssl=False,
email_box_port=False,
email_box_user="example@example.com",
email_box_pass="example",
email_box_imap_folder="INBOX",
email_message_delete=False):
def get_server():
if email_box_ssl:
ebp = 993
if email_box_port:
ebp = email_box_port
return imaplib.IMAP4_SSL(email_box_host, int(ebp))
else:
ebp = 143
if email_box_port:
ebp = email_box_port
return imaplib.IMAP4(email_box_host, int(ebp))
def get_messages():
server.login(email_box_user, email_box_pass)
server.select(email_box_imap_folder)
status, data = server.search(None, 'ALL')
for num in data[0].split():
status, data = server.fetch(num, '(RFC822)')
full_message = data[0][1]
if email_message_delete:
server.store(num, '+FLAGS', '\\Deleted')
yield parser.parsestr(full_message)
def close_server():
server.expunge()
server.close()
server.logout()
parser=Parser()
server = get_server()
return (get_messages, close_server)
# __pop3 retrieves email
def pop3_function_generator(
email_box_host="mail.example.com",
email_box_ssl=False,
email_box_port=False,
email_box_user="example@example.com",
email_box_pass="example",
email_message_delete=False):
def get_server():
if email_box_ssl:
ebp = 995 if not email_box_port else email_box_port
return poplib.POP3_SSL(email_box_host, int(ebp))
else:
ebp = 110 if not email_box_port else email_box_port
return poplib.POP3(email_box_host, int(ebp))
def get_messages():
server.getwelcome()
server.user(email_box_user)
server.pass_(email_box_pass)
messagesInfo = server.list()[1]
for msg in messagesInfo:
msgNum = msg.split(" ")[0]
msgSize = msg.split(" ")[1]
full_message = "\n".join(server.retr(msgNum)[1])
server.dele(msgNum)
yield parser.parsestr(full_message)
def close_server():
server.quit()
parser=Parser()
server = get_server()
return (get_messages, close_server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment