سؤال

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?

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

المحلول

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.

نصائح أخرى

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

You may use imap_tools package: https://pypi.org/project/imap-tools/

for message in mailbox.fetch():
    message.uid          # str or None, '123'
    message.subject      # str, 'some subject'
    message.from_        # str, 'sender@ya.ru'
    message.to           # tuple, ('iam@goo.ru', 'friend@ya.ru', )
    message.cc           # tuple, ('cc@mail.ru', )
    message.bcc          # tuple, ('bcc@mail.ru', )
    message.date         # datetime.datetime, 1900-1-1 for unparsed, may be naive or with tzinfo
    message.text         # str, 'hi'
    message.html         # str, '<b>hi</b>'
    message.flags        # tuple, ('SEEN', 'FLAGGED', 'ENCRYPTED')
    message.headers      # dict, {'Received': ('from 1.m.net', 'from 2.m.net'), 'AntiVirus-Status': ('Clean',)}
    message.attachments  # [(str, bytes)], 'cat.jpg', b'\xff\xd8\xff\xe0\'
    message.obj          # original email.message.Message object
    message.from_values  # dict or None, {'email': 'sender@ya.ru', 'name': 'Ivan', 'full': 'Ivan <sender@ya.ru>'}
    message.to_values    # tuple, ({'email': '', 'name': '', 'full': ''},)
    message.cc_values    # tuple, ({'email': '', 'name': '', 'full': ''},)
    message.bcc_values   # tuple, ({'email': '', 'name': '', 'full': ''},)
    message.date_str     # original date str, 'Tue, 03 Jan 2017 22:26:59 +0500'
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top