IMAP: how to move a message from one folder to another

此生再无相见时 提交于 2019-12-18 11:21:34

问题


(using the IMAP commands, not with the assistance of any other mail package)


回答1:


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.




回答2:


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 MOVE capability.

If it isn't available, but UIDPLUS (RFC 4315) is, the second best option is to use the combination of UID STORE, UID COPY and UID EXPUNGE:

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

If the 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.




回答3:


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[0] == 'OK':
    mov, data = obj.uid('STORE', msg_uid , '+FLAGS', '(\Deleted)')
    obj.expunge()

Where msg_uid is the uid of the mail.




回答4:


I guess you COPY the message to the new folder and then delete (EXPUNGE) it in the old one.

RFC3501

HINT There's no DELETE command that does what you mean, you have to flag the message as deleted and then EXPUNGE the mailbox. Have a look at the RFC. Be careful with DELETE, as it deletes whole mailboxes, not single mails.



来源:https://stackoverflow.com/questions/122267/imap-how-to-move-a-message-from-one-folder-to-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!