Python imaplib无需下载完整附件即可下载Gmail文本 [英] Python imaplib download Gmail Text without downloading the full attachment

查看:129
本文介绍了Python imaplib无需下载完整附件即可下载Gmail文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在python中使用"imaplib"从Gmail帐户中提取电子邮件.但是我只想知道电子​​邮件的内容,附件的标题,而无需下载完整的附件.

I am using 'imaplib' in python to fetch the email from a Gmail account. 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.

默认情况下

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.

我已经在互联网和stackOverflow上进行搜索以找到答案.其中许多人提到要使用

I've searched over the internet and stackOverflow to find answer. Many of them mentioned to use

myGmail.fetch(mailUid, 'BODYSTRUCTURE')

先确定电子邮件结构,然后确定要下载的部分.而且我还阅读了其中中有关imap4协议的RFC 3501文档.它提到我可以使用

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

BODY []<> 在Fetch命令中下载特定的身体部位.

BODY[]<> to download the specific body part in Fetch command.

但是我在python imaplib中尝试了很多命令,如下所示:

But I've tried many command in python imaplib like following:

(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:

错误:FETCH命令错误:错误['无法解析命令']

error: FETCH command error: BAD ['Could not parse command']

任何人都可以告诉我如何在适用于Gmail的python imaplib中使用此命令?

So anyone can tell me how to use this command in python imaplib for Gmail?

仅供参考,以上示例电子邮件的主体结构为:

And just for your reference, the BODYSTRUCTURE for above example email is:

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

谢谢!

推荐答案

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

这篇关于Python imaplib无需下载完整附件即可下载Gmail文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆