How to copy a message from one imap server to another imap server using Python imaplib?
Question: 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', 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?


Answer: U 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.

