Skip to content

Instantly share code, notes, and snippets.

@OdinsHat
Last active August 29, 2015 14:02
Show Gist options
  • Save OdinsHat/e1084541c119e7c3e31f to your computer and use it in GitHub Desktop.
Save OdinsHat/e1084541c119e7c3e31f to your computer and use it in GitHub Desktop.
Quick script written for reading our many company email for stock status updates from Kidkraft and then downloading the attached xlsx file for processing
#!/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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment