python-3.xmessageflagsmaildir

Python3: using mailbox.Maildir() and storing message to be marked as "Seen"?


I'm using Python3.8 to manage email on my debian server.

I have the following code which saves an email message into a maildir, where "maildir_path" is a string containing the path to the maildir, and "message_string" is a string containing a properly formatted email message ...

mdir = mailbox.Maildir(maildir_path, create=True)
mdir.lock()
mdir.add(message_string)
mdir.flush()
mdir.unlock()

This works well, as written. However in some cases, I also want the stored message to be immediately set to have "Seen" status, as soon as it is created. I know that the "S" flag can mark a message as "Seen", but I haven't been able to figure out any way using the mailbox.Maildir() object to cause the "S" flag to be applied to the generated and stored email message.

Or if mailbox.Maildir() can't itself be used for applying the "S" flag to the message, is there any other way to do that?

Thank you in advance for any ideas and suggestions for how this could be accomplished.


Solution

  • You need to retrieve the MailDirMessage object corresponding to the message. Once you have that you can use the add_flag method to set the S flag:

    mdir = mailbox.Maildir(maildir_path, create=True)
    mdir.lock()
    msgkey = mdir.add(message_string)
    
    # Get the message object
    msg = mdir.get(msgkey)
    
    # Set the "sent" flag
    msg.add_flag('S')
    
    # Update the message in the mailbox
    mdir.update([(msgkey, msg)])
    mdir.flush()
    mdir.unlock()