简体   繁体   中英

I cannot fetch a mail using imap in python

The fetch method gives this error:

imaplib.IMAP4.error: FETCH command error: BAD [b'Could not parse command']

I am not attaching all of my code. I want to get the unseen msg using imap to get the body and save it as text and then download the attachment.

import imaplib, email, os
user= "test9101997"
password="Monday@123"
imap_url="imap.gmail.com"
attach_dir='E:\PROJECT\attachment'
filePath='D:\ATTACH'     
con=imaplib.IMAP4_SSL(imap_url)
con.login(user,password)
con.select('INBOX')
#UIDs=con.search(None,'UNSEEN')
#print(UIDs)
(result, messages) = con.search(None, 'UnSeen')
if result == "OK":
   for message in messages:
        try: 
          ret, data =con.fetch(message,'(RFC822)')
        except:
             print ("No new emails to read.")
                    #self.close_connection()
                    #exit()
                    #result, data=con.fetch(i,'(RFC822)')
             raw=email.message_from_bytes(data[0][1])

I think you may be confused about the return value of con.search() . If you take a look at the value of messages after that call (assuming that result is OK ), it's collection of strings, not a list of message ids. That is, after a call like:

result, messages = con.search(None, 'UnSeen')

The value of messages may look something like:

['1 2 15 20']

So when you try to iterate over it like this:

for message in messages:

The value of message in the first loop iteration will be 1 2 15 20 , and that's why you're getting the command error: the request you're making doesn't make any sense. You'll want to do something like this instead:

(result, blocks) = con.search(None, 'UnSeen')

if result == "OK":
    for messages in blocks:
        for message in messages.split():
            ret, data = con.fetch(message, '(RFC822)')
            raw = email.message_from_bytes(data[0][1])

There's really no good reason for the imaplib module to return data in this fashion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM