Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a message from one imap server to another imap server 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', uid, 'RFC822')
connection2.uid('APPEND', None, data[0][1])

But this raises an exception:

imaplib.error: UID command error: BAD ['"Delivered-To: [email protected]']

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

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

Delivered-To: [email protected]\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: [email protected]\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?

like image 891
i.amniels Avatar asked Aug 31 '25 02:08

i.amniels


1 Answers

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'])
like image 93
i.amniels Avatar answered Sep 02 '25 14:09

i.amniels