#!/usr/bin/env python
import email
import imaplib
import os
import sys
detach_dir = '.' # directory where to save attachments (default: current)
files = os.listdir('.')
for f in files:
if os.path.splitext(f)[1] == '.xlsx':
print("Removing: %s" % f)
os.remove(f)
user = 'USER'
pwd = 'PASS'
# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
m.select()
resp, items = m.search(None, '(HEADER Subject "Stock Status")') #Search for "Stcok Status" in the subject
items = items[0].split()
items.reverse() # Get the latest first
items = items[:1]
for emailid in items:
resp, data = m.fetch(emailid, "(RFC822)")
email_body = data[0][1]
mail = email.message_from_string(email_body)
#Check if any attachments at all
if mail.get_content_maintype() != 'multipart':
print 'No attachment'
continue
print "["+mail["From"]+"] :" + mail["Subject"]
for part in mail.walk():
if part.get_content_maintype() == 'multipart':
continue
# part an attachment ?
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
counter = 1
# if there is no filename, we create one with a counter to avoid duplicates
if not filename:
filename = 'stock-%03d%s' % (counter, 'update')
counter += 1
att_path = os.path.join(detach_dir, filename)
#Check if its already there
if not os.path.isfile(att_path) :
fp = open(att_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()