简体   繁体   English

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

[英]I cannot fetch a mail using imap in python

The fetch method gives this error: fetch方法给出此错误:

imaplib.IMAP4.error: FETCH command error: BAD [b'Could not parse command'] imaplib.IMAP4.error:FETCH命令错误:BAD [b'不能解析命令']

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. 我想获取看不见的消息,使用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])

I think you may be confused about the return value of con.search() . 我认为您可能对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. 如果您在调用之后查看messages的值(假设resultOK ),则它是字符串的集合,而不是message id的列表。 That is, after a call like: 也就是说,经过如下调用:

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

The value of messages may look something like: messages的值可能类似于:

['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. 第一次循环迭代中的消息值将是1 2 15 20 ,这就是您收到命令错误的原因:您正在进行的请求没有任何意义。 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. 确实没有充分的理由让imaplib模块以这种方式返回数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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