Parsing IMAP responses in python
Asked Answered
F

3

9

I am using imaplib to work with imap in python, however it looks like it doesn't have means to parse the details of IMAP responses. For example, query like:

   msgdata = connection.fetch(num, "(BODY.PEEK[HEADER.FIELDS (FROM TO CC DATE SUBJECT MESSAGE-ID)] UID)")

where num is the message number, for one mail server may produce (for example):

  ('OK', [('1234 (BODY[HEADER.FIELDS (FROM TO CC DATE SUBJECT MESSAGE-ID)] {123}', 'From: ...etc headers'), ' UID 3456)'])

and for another:

  ('OK', [('1234 (UID 3456 BODY[HEADER.FIELDS (FROM TO CC DATE SUBJECT MESSAGE-ID)] {123}', 'From: ...etc headers'), ')'])

As you see, the message details are different and UID is even in different element there. So the question is - is there some library that would allow to automatically sort it out and abstract the details of what particular mail server does?

Flytrap answered 16/12, 2010 at 23:49 Comment(0)
A
8

Doug Hellman's Python Module of the Week entry for imaplib is a fairly extensive tutorial on the subject, but is far to long to reproduce here.

You might want to use a higher level library like IMAPClient to hide some of the details of the IMAP protocol.

Axletree answered 17/12, 2010 at 0:26 Comment(1)
Unfortunately, Doug's tutorial kind of glides over the topic of parsing more complex fetch() responses. Thanks for the link to IMAPClient, I'll check it out.Flytrap
U
3

High level IMAP lib may be useful: https://github.com/ikvk/imap_tools

from imap_tools import MailBox
# get list of email subjects from INBOX folder
with MailBox('imap.mail.com').login('[email protected]', 'password', 'INBOX') as mailbox:
    data = [(msg.uid, msg.subject) for msg in mailbox.fetch()]
Unsound answered 9/10, 2019 at 12:47 Comment(1)
this library appears to have the most dev activity of the 3, 2022-03Sinnard
L
1

Look at Imbox, you will probably find what your are looking for https://pypi.org/project/imbox/

Lavery answered 22/1, 2019 at 17:30 Comment(1)
this appears to have the most stars on github, 1.1k as of 2022-03Sinnard

© 2022 - 2024 — McMap. All rights reserved.