Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

imap-tools Access Raw Message Data

Tags:

python

smtp

imap

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('[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

like image 210
Bigbob556677 Avatar asked Aug 10 '26 09:08

Bigbob556677


2 Answers

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.

like image 177
Bigbob556677 Avatar answered Aug 12 '26 23:08

Bigbob556677


The raw message data for an email fetched with imap-tools can be accessed via the msg.obj property. To parse this into an email.message object, we can pass the raw data to email.message_from_bytes(). So the key is using msg.obj to get the raw message from imap-tools, and then load that into the email library.

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.obj
       email_message = email.message_from_bytes(raw_email)
       
       # forward or process email_message here
       

I took the obj object because according to the official documentation it is " the email.message.Message: original object" I pasted you all valid field down below so you can chose if obj is the right fo ryou

for msg in mailbox.fetch():  # generator: imap_tools.MailMessage
    msg.uid          # str | None: '123'
    msg.subject      # str: 'some subject 你 привет'
    msg.from_        # str: 'Bartö[email protected]'
    msg.to           # tuple: ('[email protected]', '[email protected]', )
    msg.cc           # tuple: ('[email protected]', )
    msg.bcc          # tuple: ('[email protected]', )
    msg.reply_to     # tuple: ('[email protected]', )
    msg.date         # datetime.datetime: 1900-1-1 for unparsed, may be naive or with tzinfo
    msg.date_str     # str: original date - 'Tue, 03 Jan 2017 22:26:59 +0500'
    msg.text         # str: 'Hello 你 Привет'
    msg.html         # str: '<b>Hello 你 Привет</b>'
    msg.flags        # tuple: ('\\Seen', '\\Flagged', 'ENCRYPTED')
    msg.headers      # dict: {'received': ('from 1.m.ru', 'from 2.m.ru'), 'anti-virus': ('Clean',)}
    msg.size_rfc822  # int: 20664 bytes - size info from server (*useful with headers_only arg)
    msg.size         # int: 20377 bytes - size of received message

    for att in msg.attachments:  # list: imap_tools.MailAttachment
        att.filename             # str: 'cat.jpg'
        att.payload              # bytes: b'\xff\xd8\xff\xe0\'
        att.content_id           # str: '[email protected]'
        att.content_type         # str: 'image/jpeg'
        att.content_disposition  # str: 'inline'
        att.part                 # email.message.Message: original object
        att.size                 # int: 17361 bytes

    msg.obj              # email.message.Message: original object
    msg.from_values      # imap_tools.EmailAddress | None
    msg.to_values        # tuple: (imap_tools.EmailAddress,)
    msg.cc_values        # tuple: (imap_tools.EmailAddress,)
    msg.bcc_values       # tuple: (imap_tools.EmailAddress,)
    msg.reply_to_values  # tuple: (imap_tools.EmailAddress,)
like image 20
pwoltschk Avatar answered Aug 12 '26 21:08

pwoltschk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!