سؤال

Using Python and imaplib I am connecting to 2 imap servers (gmail) and trying to match emails between them using the date their date time.

I am having 2 problems.

  • The date returned by parsing the header is not directly usable in searching, the format is wrong.
  • It is not clear to me which imap search to use to search by date and time as returned by parsing the header.

I have Oldmail and NewMail imap connections.

NewMail.select("[Gmail]/All Mail", readonly=True)
OldMail.select("[Gmail]/All Mail")

Just choosing a random email "6001"

typ, msg = NewMail.fetch('6001', '(BODY[HEADER])')
parser = HeaderParser()
pmsg = parser.parsestr(msg[0][1])

>>> pmsg['Date']
'Tue, 28 Dec 2010 21:56:00 -0700'

But this is not in the right formate to use like, surly there is an easy way :-)

searchfor = '(ON "' + pmsg['Date'] + '")'
>>> searchfor
'(ON "Tue, 28 Dec 2010 21:56:00 -0700")'
OldMail.search(None, searchfor)

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/imaplib.py", line 620, in search
    typ, dat = self._simple_command(name, *criteria)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/imaplib.py", line 1060, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/imaplib.py", line 895, in _command_complete
    raise self.error('%s command error: %s %s' % (name, typ, data))
error: SEARCH command error: BAD ['Could not parse command']

My goal is to find matching emails between the 2 servers after failed transfer using googles migration app. Then delete the email on the old server if they have transferred. If you can suggest a better way of doing this that would be helpful also.

هل كانت مفيدة؟

المحلول

It looks like the problem is just date formatting. In which case this:

a = datetime.strptime(pmsg['Date'],"%a, %d %b %Y %H:%M:%S %z")

will give you a date time object and this will give you the message:

searchfor = '(ON "%s")' %(a.strftime("%d-%b-%Y")

Bear in mind this will give all messages from that date, since it ignores time and timezone info.

As an alternative, it's worth looking at your emails and seeing if the "Message-Id:" header could be of help, since it should be the same on each account for genuinely duplicate emails.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top