from exchangelib import ( Credentials, Configuration, Account, DELEGATE, Message, FileAttachment, ) from pathlib import Path from typing import Iterable 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, ) class ExchangeMessage: _account = get_account("ghorel@lmcg.com") def get_msgs(self, count=None, path=["GS", "Swaptions"], **filters): folder = self._account.inbox for p in path: folder /= p folder = folder.filter(**filters) 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 def send_email( self, subject, body, to_recipients, cc_recipients=(), attach: Iterable[FileAttachment] = (), ): m = Message( account=self._account, folder=self._account.sent, subject=subject, body=body, to_recipients=to_recipients, cc_recipients=cc_recipients, ) for attachment in attach: m.attach(attachment) m.send_and_save()