Skip navigation

import email, getpass, imaplib, os

detach_dir = '.'

### directory where to save attachments (default: current)

m = imaplib.IMAP4_SSL('imap.gmail.com', 993)
m.login('username@gmail.com','password')
keywordsSearch = 'bananas oranges'
searchString = "(ALL SUBJECT '%s')" % keywordsSearch

### m.search(None, "(ALL SUBJECT 'bananas oranges')")
resp, items = m.search(None, searchString)
items = items[0].split()
for emailid in items:
    resp, data = m.fetch(emailid, "(RFC822)")
    email_body = data[0][1]
    mail = email.message_from_string(email_body)
    if mail.get_content_maintype() != 'multipart':
        continue
    print "["+mail["From"]+"] :" + mail["Subject"]
    for part in mail.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue
        filename = part.get_filename()
        counter = 1
        if not filename:
            filename = 'part-%03d%s' % (counter, 'bin')
            counter += 1
        att_path = os.path.join(detach_dir, filename)
        if not os.path.isfile(att_path) :
            fp = open(att_path, 'wb')
            fp.write(part.get_payload(decode=True))
            fp.close()

About these ads

5 Comments

  1. Hi,

    I’m trying to do something similar but I get an error:

    In [67]: resp, items = m.search(None, searchString)

    (…)

    error: command SEARCH illegal in state AUTH, only allowed in states SELECTED

    Do you know what might happened??

    • >Hi,
      >I’m trying to do something similar but I get an error:
      >In [67]: resp, items = m.search(None, searchString)
      >(…)
      >error: command SEARCH illegal in state AUTH, only allowed in states >SELECTED
      >Do you know what might happened??

      m.select()

    • I know this is old, but just in case someone comes across this,

      placing: m.select() on the line before the search solves this problem.
      :)

  2. I’m using the following to get the email attachment:
    import poplib
    from email.Parser import Parser
    pop3 = poplib.POP3(mail_host)
    pop3.user(mail_user)
    pop3.pass_(mail_passwd)

    num = len(pop3.list()[1])

    if num > 0:
    for i in range(1, num+1):
    str = string.join(pop3.top(i, 55)[1], “\n”)
    msg = Parser().parsestr(str)
    n=0
    text=”
    #Check if any attachments at all
    if msg.get_content_maintype() != ‘multipart’:
    print ‘No attachments in message’
    return

    for part in msg.walk():
    if n==1:
    text=part.get_payload()
    n+=1
    if part.get_content_maintype() == ‘multipart’:
    continue
    if part.get(‘Content-Disposition’) is None:
    continue
    filename = part.get_filename()
    counter = 1
    if not filename:
    filename = ‘part-%03d%s’ % (counter, ‘bin’)
    counter += 1
    att_path = os.path.join(detach_dir, filename)
    if not os.path.isfile(att_path) :
    fp = open(att_path, ‘wb’)
    fp.write(part.get_payload(decode=True))
    fp.close()

    From=msg['From']
    Subject=msg['subject']
    #parse ‘from’ text
    if From.find(‘<')!=-1:
    start=From.find('’)
    From=From[(start+1):end]
    body=text.split(‘\n’)
    emailBody=text
    #pop3.dele(i)

    It seems to work fine, but when I look at the resulting file (XLS file), it’s 1k big and can’t even be opened. What am I doing wrong?

  3. Hi there,

    I get a error like:
    imaplib.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED

    any suggestions?
    tx

    hugo


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: