Skip to content

Instantly share code, notes, and snippets.

@kennyledet
Created April 27, 2013 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kennyledet/5474964 to your computer and use it in GitHub Desktop.
Save kennyledet/5474964 to your computer and use it in GitHub Desktop.
Shows how to access Gmail (or any other IMAP4 server) for new messages under a certain folder or label name. Comments are fairly straightforward; shows how to also get attachments if any exist.
import imaplib
folder_name = 'Inbox'
gm = imaplib.IMAP4_SSL('imap.gmail.com', 993)
gm.login('youraddress@gmail.com', 'password')
status, data = gm.select(folder_name) # select() can select by label or folder name
if status: status, data = gm.search(None, 'UNSEEN') # get new messages only
# Loop through unseen messages
for num in data[0].split():
status, data = gm.fetch(num, '(RFC822)')
raw_email = data[0][1]
msg = email.message_from_string(raw_email)
maintype = msg.get_content_maintype()
print msg['Subject']
print 'Main Type: ', maintype
if maintype == 'multipart':
for part in msg.walk():
part_type = part.get_content_type()
if part_type == 'application/octet-stream' or 'image' in part_type:
filename = part.get_filename()
print filename
data = part.get_payload(decode=1) # get the file's binary data for writing
with open(filename, 'wb') as out:
out.write(data)
elif part_type == 'text/html':
msg_content = part.get_payload()
elif maintype == 'text':
msg_content = msg.get_payload()
typ, data = gm.store(num,'-FLAGS','\\Seen') # mark as seen
gm.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment