0

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?

I prefer to reuse :-)

Community
  • 1
  • 1
guettli
  • 25,042
  • 81
  • 346
  • 663

3 Answers3

6

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.

Community
  • 1
  • 1
ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
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.uids(), '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.uids('(UNSEEN)'), flags, True)

    # SEEN: mark all messages sent at 05.03.2007 in current folder as unseen, *in bulk
    mailbox.seen(mailbox.uids("SENTON 05-Mar-2007"), False)
Vladimir
  • 6,162
  • 2
  • 32
  • 36
0

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...").

Community
  • 1
  • 1
Jan Kundrát
  • 3,700
  • 1
  • 18
  • 29
  • The command might is fresh in the IMAP spec. Yes, that's true. But the use case is very old. I use IMAPClient now, and talked to the maintainer, since it does not `move` up to now. – guettli Mar 02 '15 at 12:23