28

I want to parse some emails from a user 's inbox but when I do:

typ, msg_data = imap_conn.fetch(uid, '(RFC822)')

It marks the email as SEEN or read. This is not the desired functionality. Do you know how can I keep the email at its previous stare either SEEN or NOT SEEN?

PanosJee
  • 3,866
  • 6
  • 36
  • 49

4 Answers4

46

You might also set read_only to true when selecting the folder:

imap_conn.select('Inbox', readonly=True)
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
lezardo
  • 476
  • 5
  • 2
  • 2
    This is unsuitable if you want to modify the folder for other reasons (say, remove some of the messages you have peeked at because they are spam, or whatever). – tripleee Jun 22 '16 at 08:19
  • You may call `imap_conn.select('Inbox')` before modifying the folder and then `imap_conn.select('Inbox', readonly=True)` again. It's simpler and more reliable to use PEEK, of course. – Ilya Semenov Oct 23 '19 at 05:09
23

The following should work:

typ, msg_data = imap_conn.fetch(uid, '(BODY.PEEK[HEADER])')

or BODY.PEEK[TEXT], etc.

ars
  • 120,335
  • 23
  • 147
  • 134
3

You can use (RFC822.PEEK) as the "message-parts" argument, according to RFC 1730 (I have not verified which servers actually implement that correctly, but it doesn't seem hard for them to).

Community
  • 1
  • 1
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 1
    Unfortunately it did not work with Gmail but the previous answer did. Thank you anyway! – PanosJee Jul 19 '10 at 18:27
  • 2
    RFC1730 is long since obsoilete. The [RFC3501](https://tools.ietf.org/html/rfc3501) equivalent is `BODY.PEEK[]` – tripleee Mar 05 '19 at 08:49
0

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

from imap_tools import MailBox, Q

# get list of email subjects from INBOX folder
with MailBox('imap.mail.com').login('test@mail.com', 'password') as mailbox:
    # mark_seen=False - not mark emails as seen on fetch
    subjects = [msg.subject for msg in mailbox.fetch(mark_seen=False)]
Vladimir
  • 6,162
  • 2
  • 32
  • 36