There are multiple ways to do that. The best one is the
UID MOVE command defined in RFC 6851 from early 2013:
C: a UID MOVE 42:69 foo S: * OK [COPYUID 432432 42:69 1202:1229] S: * 22 EXPUNGE S: (more expunges) S: a OK Done
Presence of this extension is indicated by the
If it isn’t available, but
UIDPLUS (RFC 4315) is, the second best option is to use the combination of
UID COPY and
C: a01 UID COPY 42:69 foo S: a01 OK [COPYUID 432432 42:69 1202:1229] Copied C: a02 UID STORE 42:69 +FLAGS.SILENT (Deleted) S: a02 OK Stored C: a03 UID EXPUNGE 42:69 S: * 10 EXPUNGE S: * 10 EXPUNGE S: * 10 EXPUNGE S: a03 Expunged
UIDPLUS is missing, there is nothing reasonable that you can do — the
EXPUNGE command permanently removes all messages which are marked for deletion, including those which you have not touched. The best this is to just use the
UID COPY and
UID STORE in that case.
I’m not sure how well-versed you are in imap-speak, but basically after login, “SELECT” the source mailbox, “COPY” the messages, and “EXPUNGE” the messages (or “DELETE” the old mailbox if it is empty now :-).
a login a s b select source c copy 1 othermbox d store 1 +flags (Deleted) e expunge
would be an example of messages to send. (Note: imap messages require a uniqe prefix before each command, thus the “a b c” in front)
See RFC 2060 for details.
If you have the uid of the email which is going to be moved.
import imaplib obj = imaplib.IMAP4_SSL('imap.gmail.com', 993) obj.login('username', 'password') obj.select(src_folder_name) apply_lbl_msg = obj.uid('COPY', msg_uid, desti_folder_name) if apply_lbl_msg == 'OK': mov, data = obj.uid('STORE', msg_uid , '+FLAGS', '(Deleted)') obj.expunge()
Where msg_uid is the uid of the mail.