Python IMAPClient 库和电子邮件包之间的交互
Interaction between Python IMAPClient library and email package
我有一个 Django 项目,我正在其中开发电子邮件客户端。我决定使用 python 的 IMAPClient instead of standard library's imaplib
for getting access to the messages. Currently, I don't make use of python's email package to encode/decode responses received from IMAPClient, and I have a feeling that I manually implement things that should be handled by email.
下载附件的示例代码:
def download_attachment(server, msgid, index, encoding):
# index and encoding is known from previous analysis of bodystructure
file_content = f_fetch(server, msgid, index)
# the below code should be handled by email's message_from_bytes
# and subsequent get_payload(decode = True) function
if encoding == 'base64':
file_content = base64.b64decode(file_content)
elif ...
...
endif
#writing file_content to a folder
return
def f_fetch(server, msgid, index):
if not index:
index = '1'
response = server.fetch(msgid, 'BODY[' + index + ']')
key = ('BODY[' + index + ']').encode('utf-8')
if type(msgid) is str:
msgid = int(msgid)
return response[msgid][key]
所以问题是,我应该如何重写这段代码以利用email。
具体来说,我应该如何处理 IMAPClient 的响应以将其传递给电子邮件的 message_from_bytes() 函数?
如果您希望使用电子邮件包的 message_from_bytes() 函数解析电子邮件,那么您需要为其提供完整的原始电子邮件正文。要得到这个,使用 RFC822
选择器像这样获取:
fetch_data = server.fetch(msgid, ['RFC822'])
parsed = email.message_from_bytes(fetch_data[msgid][b'RFC822'])
如果您从 IMAP 服务器中提取单个邮件 parts/attachments,则服务器会有效地为您完成解析工作,您不需要使用电子邮件包的解析器。
我有一个 Django 项目,我正在其中开发电子邮件客户端。我决定使用 python 的 IMAPClient instead of standard library's imaplib
for getting access to the messages. Currently, I don't make use of python's email package to encode/decode responses received from IMAPClient, and I have a feeling that I manually implement things that should be handled by email.
下载附件的示例代码:
def download_attachment(server, msgid, index, encoding):
# index and encoding is known from previous analysis of bodystructure
file_content = f_fetch(server, msgid, index)
# the below code should be handled by email's message_from_bytes
# and subsequent get_payload(decode = True) function
if encoding == 'base64':
file_content = base64.b64decode(file_content)
elif ...
...
endif
#writing file_content to a folder
return
def f_fetch(server, msgid, index):
if not index:
index = '1'
response = server.fetch(msgid, 'BODY[' + index + ']')
key = ('BODY[' + index + ']').encode('utf-8')
if type(msgid) is str:
msgid = int(msgid)
return response[msgid][key]
所以问题是,我应该如何重写这段代码以利用email。 具体来说,我应该如何处理 IMAPClient 的响应以将其传递给电子邮件的 message_from_bytes() 函数?
如果您希望使用电子邮件包的 message_from_bytes() 函数解析电子邮件,那么您需要为其提供完整的原始电子邮件正文。要得到这个,使用 RFC822
选择器像这样获取:
fetch_data = server.fetch(msgid, ['RFC822'])
parsed = email.message_from_bytes(fetch_data[msgid][b'RFC822'])
如果您从 IMAP 服务器中提取单个邮件 parts/attachments,则服务器会有效地为您完成解析工作,您不需要使用电子邮件包的解析器。