from exchangelib import Credentials, Configuration, Account, DELEGATE from pathlib import Path import json def get_account(email_address): with open(Path('.credentials') / (email_address + '.json')) as fh: creds = json.load(fh) credentials = Credentials(**creds) config = Configuration(server='autodiscover.lmcg.com', credentials=credentials) return Account(primary_smtp_address=email_address, config=config, autodiscover=False, access_type=DELEGATE) def get_msgs(account=None, email_address='ghorel@lmcg.com', count=None, path=['GS', 'Swaptions'], subject_filter=None): if account is None: account = get_account(email_address) folder = account.inbox for p in path: folder /= p if subject_filter is not None: folder = folder.filter(subject__contains=subject_filter) if count: for msg in folder.all().order_by('-datetime_sent')[:count]: yield msg else: for msg in folder.all().order_by('-datetime_sent'): yield msg