#!/usr/bin/env python3
# imap_client_list_folders.py
# 2023-05-10
# by Gernot Walzl
import argparse
import getpass
import imaplib
class IMAPClient:
def __init__(self, server):
self._mail = imaplib.IMAP4_SSL(server)
def login(self, username, password):
self._mail.login(username, password)
def list_folders(self):
folders = []
for list_element in self._mail.list()[1]:
folder = list_element.decode().split(' "/" ')[1]
folders.append(folder)
return folders
def count_messages(self, folder):
return int(self._mail.select(folder)[1][0].decode())
def main(server, username, password):
mail_client = IMAPClient(server)
mail_client.login(username, password)
for folder in mail_client.list_folders():
num_messages = mail_client.count_messages(folder)
print("{} {}".format(folder, num_messages))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("server", type=str)
parser.add_argument("username", type=str)
args = parser.parse_args()
main(args.server, args.username, getpass.getpass())