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

前端 未结 4 428
故里飘歌
故里飘歌 2020-12-28 16:44

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

相关标签:
4条回答
  • 2020-12-28 17:05

    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.

    0 讨论(0)
  • 2020-12-28 17:21

    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.

    0 讨论(0)
  • 2020-12-28 17:22

    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.

    0 讨论(0)
  • 2020-12-28 17:23

    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.

    0 讨论(0)
提交回复
热议问题