imaplib: is this really so unwieldy?

hw hw at adminart.net
Tue May 25 04:23:41 EDT 2021


Hi,

I'm about to do stuff with emails on an IMAP server and wrote a program 
using imaplib which, so far, gets the UIDs of the messages in the inbox:


#!/usr/bin/python

import imaplib
import re

imapsession = imaplib.IMAP4_SSL('imap.example.com', port = 993)

status, data = imapsession.login('user', 'password')
if status != 'OK':
     print('Login failed')
     exit

messages = imapsession.select(mailbox = 'INBOX', readonly = True)
typ, msgnums = imapsession.search(None, 'ALL')
message_uuids = []
for number in str(msgnums)[3:-2].split():
     status, data = imapsession.fetch(number, '(UID)')
     if status == 'OK':
         match = re.match('.*\(UID (\d+)\)', str(data))
         message_uuids.append(match.group(1))
for uid in message_uuids:
     print('UID %5s' % uid)

imapsession.close()
imapsession.logout()


It's working (with Cyrus), but I have the feeling I'm doing it all wrong 
because it seems so unwieldy.  Apparently the functions of imaplib 
return some kind of bytes while expecting strings as arguments, like 
message numbers must be strings.  The documentation doesn't seem to say 
if message UIDs are supposed to be integers or strings.

So I'm forced to convert stuff from bytes to strings (which is weird 
because bytes are bytes) and to use regular expressions to extract the 
message-uids from what the functions return (which I shouldn't have to 
because when I'm asking a function to give me a uid, I expect it to 
return a uid).

This so totally awkward and unwieldy and involves so much overhead that 
I must be doing this wrong.  But am I?  How would I do this right?


More information about the Python-list mailing list