我无法在 python 中使用 imap 获取邮件

I cannot fetch a mail using imap in python

fetch 方法给出了这个错误:

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

我没有附上我的所有代码。我想通过imap获取未看到的消息,获取正文并将其保存为文本,然后下载附件。

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])

我想您可能对 con.search() 的 return 值感到困惑。如果您在该调用后查看 messages 的值(假设 resultOK),它是字符串集合,而不是消息 ID 列表。也就是说,在像这样的电话之后:

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

messages 的值可能类似于:

['1 2 15 20']

所以当你尝试像这样迭代它时:

for message in messages:

第一次循环迭代中消息的值将为 1 2 15 20,这就是您收到命令错误的原因:您发出的请求没有任何意义。你会想做这样的事情:

(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])

imaplib 模块以这种方式 return 数据确实没有充分的理由。