Skip to content

Instantly share code, notes, and snippets.

@OdinsHat
Created May 18, 2014 08:12
Show Gist options
  • Save OdinsHat/241b3623ec5f6781c6ff to your computer and use it in GitHub Desktop.
Save OdinsHat/241b3623ec5f6781c6ff to your computer and use it in GitHub Desktop.
Quick & dirty script used for downloading latest stock sheet from Google Apps Email and saving to server for further processing
#!/usr/bin/env python
""" Quick & dirty script used for downloading latest stock sheet from
Google Apps Email and saving to server for further processing"""
import email
import imaplib
import os
save_dir = '.'
user = 'GMAILEMAIL'
pwd = 'GMAILPASSWORD'
def search_emails(imapsearch='(HEADER Subject "Stock Status")'):
"""
Given an IMAP search string search the emails for the stock update email
"""
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
m.select()
resp, items = m.search(None, imapsearch)
items = items[0].split()
items.reverse()
items = items[:1]
return items
def wipe_existing(save_dir, extension):
files = os.listdir(save_dir)
for f in files:
if os.path.splitext(f)[1] == ('.%s' % extension):
print("Removing: %s" % f)
os.remove(f)
def main(save_dir, user, pwd):
wipe_existing(save_dir, 'xlsx')
items = search_emails()
for emailid in items:
resp, data = m.fetch(emailid, "(RFC822)")
email_body = data[0][1] # getting the mail content
mail = email.message_from_string(email_body) # parsing the mail content to get a mail object
#Check if any attachments at all
if mail.get_content_maintype() != 'multipart':
print 'No attachment'
continue
print "[%s]: %s" % (mail["From"], mail["Subject"])
for part in mail.walk():
# multipart are just containers, so we skip them
if part.get_content_maintype() == 'multipart':
continue
# is this part an attachment ?
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
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()
if __name__ == "__main__":
main(save_dir, user, pwd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment