Subversion Repositories SmartDukaan

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
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)
17
    resp, items = m.search(None, 'SUBJECT', subject, 'SENTON', date)
18
    items = items[0].split() # getting the mail ids
19
    items.sort(reverse=True)
20
 
21
    attachment_path = None
22
 
23
    for emailid in items:
24
        # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
25
        resp, data = m.fetch(emailid, "(RFC822)")
26
        email_body = data[0][1] # getting the mail content
27
        mail = email.message_from_string(email_body) # parsing the mail content to get a mail object
28
 
29
        #Check if any attachments at all
30
        if mail.get_content_maintype() != 'multipart':
31
            continue
32
 
33
        print "["+mail["From"]+"] :" + mail["Subject"]
34
 
35
        # we use walk to create a generator so we can iterate on the parts and forget about the recursive headach
36
        for part in mail.walk():
37
            # multipart are just containers, so we skip them
38
            if part.get_content_maintype() == 'multipart':
39
                continue
40
 
41
            # is this part an attachment ?
42
            if part.get('Content-Disposition') is None:
43
                continue
44
 
45
            filename = part.get_filename()
46
            counter = 1
47
 
48
            # if there is no filename, we create one with a counter to avoid duplicates
49
            if not filename:
50
                filename = 'part-%03d%s' % (counter, 'bin')
51
                counter += 1
52
 
53
            attachment_path = os.path.join(detach_dir, filename)
54
 
55
            #Check if its already there
56
            if not os.path.isfile(attachment_path) :
57
                # finally write the stuff
58
                fp = open(attachment_path, 'wb')
59
                fp.write(part.get_payload(decode=True))
60
                fp.close()
61
 
62
        #We are only expecting a single email per day with a given subject.
63
        break
64
    return attachment_path