简体   繁体   English

Python imaplib无需下载完整附件即可下载Gmail文本

[英]Python imaplib download Gmail Text without downloading the full attachment

I am using 'imaplib' in python to fetch the email from a Gmail account. 我在python中使用“ imaplib”从Gmail帐户中提取电子邮件。 But I just want to know the content of the email, the title of the attachment, but do not need to download the full attachment. 但我只想知道电子​​邮件的内容,附件的标题,而无需下载完整的附件。

By default, 默认,

myGmail = imaplib.IMAP4_SSL(...)
....
(respCode, data) = myGmail.fetch(mailUid, 'RFC822')

will return the whole part of email, including the whole attachment encoded as text in the return data, which is sometimes huge and unnecessary. 将返回电子邮件的整个部分,包括在返回数据中编码为文本的整个附件,有时这是巨大且不必要的。

I've searched over the internet and stackOverflow to find answer. 我已经在互联网和stackOverflow上进行搜索以找到答案。 Many of them mentioned to use 其中许多提到使用

myGmail.fetch(mailUid, 'BODYSTRUCTURE')

to determined the email structure first, and then identify the part you want download. 首先确定电子邮件结构,然后确定要下载的部分。 And I have also read the RFC 3501 doc about imap4 protocol, in which it mentioned that I can use 我还阅读了有关imap4协议的RFC 3501文档, 其中提到我可以使用

BODY[]<> to download the specific body part in Fetch command. BODY [] <>以在Fetch命令中下载特定的身体部位。

But I've tried many command in python imaplib like following: 但是我已经在python imaplib中尝试了很多命令,如下所示:

(rCode, data) = myGmail.fetch(mailUid, 'BODY[0]')
(rCode, data) = myGmail.fetch(mailUid, 'BODY0')
(rCode, data) = myGmail.fetch(mailUid, 'BODY[TEXT]')

but all of them failed with error message: 但是它们全部失败,并显示错误消息:

error: FETCH command error: BAD ['Could not parse command'] 错误:FETCH命令错误:错误['无法解析命令']

So anyone can tell me how to use this command in python imaplib for Gmail? 因此,任何人都可以告诉我如何在适用于Gmail的python imaplib中使用此命令?

And just for your reference, the BODYSTRUCTURE for above example email is: 仅供参考,以上示例电子邮件的BODYSTRUCTURE为:

(BODY 
 (
  (
    (
      ("TEXT" "PLAIN" ("CHARSET" "us-ascii") NIL NIL "QUOTED-PRINTABLE" 1742 33)
      ("TEXT" "HTML" ("CHARSET" "us-ascii") NIL NIL "QUOTED-PRINTABLE" 17976 485) "ALTERNATIVE"
    )
    (
      "IMAGE" "JPEG" 
      ("NAME" "image001.jpg") "<image001.jpg@01CD029F.6831C440>" "image001.jpg" "BASE64" 4070
    ) 
    "RELATED"
  )
  ("APPLICATION" "PDF" ("NAME" "SAC 2012.pdf") NIL "SAC 2012.pdf" "BASE64" 20638)
  "MIXED"
 )
 )

Thanks!!! 谢谢!!!

只需将BODY[0]替换为(BODY[1])

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

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