Skip to content Skip to sidebar Skip to footer

Move Mail In IMAP With Python Library

Moving a message to a different folder seems quite difficult in IMAP. See IMAP: how to move a message from one folder to another How can I do this in Python without coding too much

Solution 1:

The imaplib standard module is at your service.

Apart from the method in the linked question, you can use a nonstandard MOVE command with IMAP4._simple_command (see copy() implementation, its syntax is the same) after checking self.capabilities for "MOVE" presence.


Solution 2:

You may use imap_tools package: https://pypi.org/project/imap-tools/

with MailBox('imap.mail.com').login('test@mail.com', 'pwd', initial_folder='INBOX') as mailbox:

    # COPY all messages from current folder to folder1, *by one
    for msg in mailbox.fetch():
        res = mailbox.copy(msg.uid, 'INBOX/folder1')

    # MOVE all messages from current folder to folder2, *in bulk (implicit creation of uid list)
    mailbox.move(mailbox.fetch(), 'INBOX/folder2')

    # DELETE all messages from current folder, *in bulk (explicit creation of uid list)
    mailbox.delete([msg.uid for msg in mailbox.fetch()])

    # FLAG unseen messages in current folder as Answered and Flagged, *in bulk.
    flags = (imap_tools.StandardMessageFlags.ANSWERED, imap_tools.StandardMessageFlags.FLAGGED)
    mailbox.flag(mailbox.fetch('(UNSEEN)'), flags, True)

    # SEEN: mark all messages sent at 05.03.2007 in current folder as unseen, *in bulk
    mailbox.seen(mailbox.fetch("SENTON 05-Mar-2007"), False)

Solution 3:

The question which you linked to has an answer which explains what the features of the IMAP protocol are. Chances are that such a command is too fresh to be available via the Python's standard imaplib. If that is the case, your best bet is to send them a patch so that it is included in future releases. That's how it works -- if nobody bothers to add support for new commands, it won't get added.

The imaplib is a rather low-level package, so I do not expect that it will ever implement a nice way of moving messages around. My suggestion would be to either use another library which provides a higher-level view of IMAP ("hey server, how many messages are there in INBOX? Show me the MIME structure of the last one, please...").


Post a Comment for "Move Mail In IMAP With Python Library"