I have a little tool that exists because my email client does not support IMAP Push extensions as implemented by gmail. Typical usage is something like this:
live-email -n 10
Which shows the id and subject of the first 10.
So some example output might be:
1242: Hello!
1241: Your email
1240: Re:
...
The code (simplified for this question) is the following:
#!/usr/bin/env python3
from imaplib import IMAP4_SSL
from netrc import netrc
from email import message_from_bytes
from argparse import ArgumentParser
parser = ArgumentParser(description='Check email')
parser.add_argument('-n', '--count', dest='count', action='store',
default=1, type=int,
help='How many messages to show')
args = parser.parse_args()
conn = IMAP4_SSL('imap.gmail.com')
auth = netrc().hosts['imap.gmail.com']
conn.login(auth[0], auth[2])
conn.select()
typ, data = conn.search(None, 'ALL')
i = 0
for num in reversed(data[0].split()):
i += 1
typ, data = conn.fetch(num, '(RFC822)')
email = message_from_bytes(data[0][1])
print("%i: %s" % (int(num), email.get('subject')))
if i == args.count:
break
conn.close()
conn.logout()
The above works. The problem is that the act of fetching each email marks it as read. I'd like to leave the state of the email alone. I suspect I'd know how to do this if I knew more about IMAP but I alas do not know that protocol. Any ideas?