开发者

How to copy a message from one imap server to another imap server using Python imaplib?

开发者 https://www.devze.com 2023-01-25 05:36 出处:网络
I want to copy a message from one IMAP server to another IMAP server. I don\'t want to alter any of the message data. I\'m using python imaplib.

I want to copy a message from one IMAP server to another IMAP server. I don't want to alter any of the message data. I'm using python imaplib.

This is the code I tried:

typ, data = connection1.uid('FETCH',开发者_如何学JAVA uid, 'RFC822')
connection2.uid('APPEND', None, data[0][1])

But this raises an exception:

imaplib.error: UID command error: BAD ['"Delivered-To: niels@domain.com']

So the argument (data[0][1]) is not properly formatted I think.

The contents of data[0][1] look like this:

Delivered-To: niels@domain.com\r\nReceived: by 10.216.207.222 with SMTP id n27cs38120weo;\r\nFri, 12 Nov 2010 09:43:47 -0800 (PST)\r\nReceived: by 10.200.19.19 with SMTP id y19mr234526eba.52.12894526694;\r\nFri, 12 Nov 2010 09:43:46 -0800 (PST)\r\nReturn-Path: somename@domain.com\r\nReceived: from dub0-omc1-s20.dub03.hotmail.com (dub0-omc1-s20.dub03.hotmail.com [157.55.0.220])\r\n ......

How can I fix this?

Update: With the help of Wodin and Avadhesh I can append messages now, but how do I get the UID of a just appended message?


You can try the follwing code:

typ, data = connection1.uid('FETCH', uid, 'RFC822')
import email
msg_str = email.message_from_string(data[0][1])
msg_create = connection2.append(str(dest_fold_code) , flags, '', str(msg_str))

where flags would be '(\Seen)' in case of seen email or '' in case of unseen email.


Have you tried:

connection2.append(mailbox, flags, date_time, message)
    Append message to named mailbox.

RFC3501 shows the syntax of the UID command as follows:

uid             = "UID" SP (copy / fetch / search / store)

i.e. there appears not to be a "UID APPEND" command.


Solved it!

First copy the message with

typ, data = connection1.uid('FETCH', uid, 'RFC822')
connection2.append('Inbox', '', '', data[0][1])

Then fetch the unique message-id from the copied message like this

from email.parser import Parser
parser = Parser()
msg = parser.parsestr(data[0][1])

Then use the message-id to find the new message in the destination mailbox like this

typ, uid = connection2.uid('SEARCH', None, 'Header', 'Message-Id', msg['message-ID'])
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号