| 1132 |
chandransh |
1 |
|
|
|
2 |
import email
|
|
|
3 |
import imaplib
|
|
|
4 |
import os
|
|
|
5 |
|
|
|
6 |
def download_attachment(subject, date):
|
|
|
7 |
detach_dir = '.' # directory where to save attachments (default: current)
|
|
|
8 |
user = 'cnc.center@shop2020.in'
|
|
|
9 |
pwd = '5h0p2o2o'
|
|
|
10 |
|
|
|
11 |
# connecting to the gmail imap server
|
|
|
12 |
m = imaplib.IMAP4_SSL("imap.gmail.com")
|
|
|
13 |
m.login(user,pwd)
|
|
|
14 |
m.select("Inbox", True) # use m.list() to get all the mailboxes
|
|
|
15 |
|
|
|
16 |
# you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)
|
| 4572 |
phani.kuma |
17 |
resp, items = m.search(None, 'SUBJECT', subject, 'UNKEYWORD', 'processed')
|
| 1132 |
chandransh |
18 |
items = items[0].split() # getting the mail ids
|
|
|
19 |
|
|
|
20 |
attachment_path = None
|
|
|
21 |
|
| 4572 |
phani.kuma |
22 |
for emailid in reversed(items):
|
| 1132 |
chandransh |
23 |
# fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
|
|
|
24 |
resp, data = m.fetch(emailid, "(RFC822)")
|
|
|
25 |
email_body = data[0][1] # getting the mail content
|
|
|
26 |
mail = email.message_from_string(email_body) # parsing the mail content to get a mail object
|
|
|
27 |
|
|
|
28 |
#Check if any attachments at all
|
|
|
29 |
if mail.get_content_maintype() != 'multipart':
|
|
|
30 |
continue
|
|
|
31 |
|
| 4572 |
phani.kuma |
32 |
print "["+mail["From"]+"] :" + mail["Subject"] + ":" + mail["Date"]
|
| 1132 |
chandransh |
33 |
|
|
|
34 |
# we use walk to create a generator so we can iterate on the parts and forget about the recursive headach
|
|
|
35 |
for part in mail.walk():
|
|
|
36 |
# multipart are just containers, so we skip them
|
|
|
37 |
if part.get_content_maintype() == 'multipart':
|
|
|
38 |
continue
|
|
|
39 |
|
|
|
40 |
# is this part an attachment ?
|
|
|
41 |
if part.get('Content-Disposition') is None:
|
|
|
42 |
continue
|
|
|
43 |
|
|
|
44 |
filename = part.get_filename()
|
|
|
45 |
counter = 1
|
|
|
46 |
|
|
|
47 |
# if there is no filename, we create one with a counter to avoid duplicates
|
|
|
48 |
if not filename:
|
|
|
49 |
filename = 'part-%03d%s' % (counter, 'bin')
|
|
|
50 |
counter += 1
|
|
|
51 |
|
|
|
52 |
attachment_path = os.path.join(detach_dir, filename)
|
|
|
53 |
|
|
|
54 |
#Check if its already there
|
|
|
55 |
if not os.path.isfile(attachment_path) :
|
|
|
56 |
# finally write the stuff
|
|
|
57 |
fp = open(attachment_path, 'wb')
|
|
|
58 |
fp.write(part.get_payload(decode=True))
|
|
|
59 |
fp.close()
|
|
|
60 |
|
|
|
61 |
#We are only expecting a single email per day with a given subject.
|
|
|
62 |
break
|
| 4572 |
phani.kuma |
63 |
try:
|
|
|
64 |
m.select("Inbox", False)
|
|
|
65 |
m.store(','.join(items), 'FLAGS', 'processed')
|
|
|
66 |
except:
|
|
|
67 |
pass
|
| 1132 |
chandransh |
68 |
return attachment_path
|