imap-tools 访问原始消息数据

问题描述 投票:0回答:1

使用 imap-tools 时如何访问电子邮件的原始消息数据? 具体来说就是可以将其加载到 email.message_from_bytes() 函数中进行转发?

from imap_tools import MailBox, AND
with MailBox('imap.gmail.com').login('[email protected]', '123456', 'INBOX') as mailbox:
    # get unseen emails from INBOX folder
    for msg in mailbox.fetch(AND(seen=False), mark_seen=False):
        pass # get the raw data from msg

python smtp imap
1个回答
0
投票

可以通过

msg.raw
属性访问使用 imap-tools 获取的电子邮件的原始消息数据。其中包含 RFC822 格式的原始电子邮件。要将其解析为 email.message 对象,我们可以将原始数据传递给
email.message_from_bytes()
。 所以关键是使用
msg.raw
从 imap-tools 获取原始消息字节,然后将其加载到电子邮件库中。

from imap_tools import MailBox, AND
import email

with MailBox('imap.gmail.com').login('[email protected]', '123456', 'INBOX') as mailbox:
   for msg in mailbox.fetch(AND(seen=False), mark_seen=False):
       raw_email = msg.raw
       email_message = email.message_from_bytes(raw_email)
       
       # forward or process email_message here
       
© www.soinside.com 2019 - 2024. All rights reserved.