Search code examples
pythonsmtpimap

imap-tools Access Raw Message Data


How do you access the raw message data of an email when using imap-tools? Specifically so it can then be loaded into the email.message_from_bytes() function for forwarding?

from imap_tools import MailBox, AND
with MailBox('imap.gmail.com').login('asdf@gmail.com', '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


Solution

  • According to the source it looks like the msg.obj property contains the value after message_from_bytes has been run.

    class MailMessage:
        """The email message"""
        def __init__(self, fetch_data: list):
            raw_message_data, raw_uid_data, raw_flag_data = self._get_message_data_parts(fetch_data)
            self._raw_uid_data = raw_uid_data
            self._raw_flag_data = raw_flag_data
            self.obj = email.message_from_bytes(raw_message_data)
    

    So msg.obj can be used directly.