I have a method that filters emails from an Outlook mailbox based on the sender and optionally, the subject and the body content (either or both). I’m using the exchangelib library to access the Exchange server.
Below is a simplified version of my code:
from typing import Literal
from exchangelib import Account, Credentials, Q
class EmailClient:
def __init__(self) -> None:
self.receiver_email = "[email protected]"
self.receiver_un = "username"
self.receiver_pw = "password"
def filter_inbox(self,
sender_address: str,
required_subj_part: str = "",
required_body_part: str = "",
both_operator: Literal["or", "and"] = "or") -> None:
subj_query = Q(subject__contains=required_subj_part)
body_query = Q(body__contains=required_body_part)
if required_subj_part and required_body_part:
if both_operator == "or":
query = subj_query | body_query
elif both_operator == "and":
query = subj_query & body_query
else:
raise ValueError("'both_operator' must be one of: 'or', 'and'")
elif required_subj_part:
query = subj_query
elif required_body_part:
query = body_query
else:
query = Q()
account = Account(self.receiver_email, autodiscover=True,
credentials=Credentials(self.receiver_un, self.receiver_pw))
for item in account.inbox.filter(query, sender=sender_address):
subject = item.subject
body = item.body.strip()
print(f"{subject=}")
print(f"{body=}", end="nn")
if __name__ == "__main__":
ec = EmailClient()
body_filter = "BBB"
ec.filter_inbox("[email protected]", required_body_part=body_filter)
I’m facing an issue where filtering emails based only on the body content also includes results that match the subject.
For instance, I have 3 mails in the inbox related to the sender:
- Subject: ‘AAA BBB’ | Body: ‘AAA BBB’
- Subject: ‘BBB’ | Body: ‘AAA’
- Subject: ‘AAA’ | Body: ‘BBB’
Even though email number 2 does not contain ‘BBB’ in its body, it is still included in the results of the filtering (because it has ‘BBB’ in the subject).
Is there a way to ensure that the filtering applies only to the body when that is the only specified criterion?
Any assistance or suggestions would be greatly appreciated. Thank you!