Python O365 library detect encrypted Emails

272 Views Asked by At

I am trying to detect if incoming emails to my O365 account is encrypted or not.

The email sender can use any email provider like Gmail, Outlook, Yahoo etc.

At the moment i am able to detect encrypted message from outlook with below condition: len(list(filter(lambda x: x.name.lower().endswith(".rpmsg"), message.attachments))) > 0 where message is O365 Message object.

Is there a more general method i can use?

PS - Python O365 or any built in libraries are preferrable

2

There are 2 best solutions below

0
On

The general solution would be to look at email headers and check if they state that the message is encrypted. I'm not sure that there is a standard for that, so you may have to sample headers in some of your encrypted messages to find a common pattern. There are some examples for S/MIME encrypted email here: https://github.com/ecederstrand/exchangelib/issues/331 but Exchange also has its own encryption solution (see https://github.com/ecederstrand/exchangelib/issues/545).

So, you need to get hold of the raw MIME content of the message, and use the built-in email module to parse that content, like @pravash05 provided some code example for.

0
On

You can check if an incoming email is encrypted by looking at the "Received" headers in the email message, which contains information about how the message was routed from the sender's mail server to your mail server

There is 0365 library, that can give access the email headers with the headers attribute of the message

from O365 import Account

account = Account(credentials=('client_id', 'client_secret'), tenant_id='tenant_id')
mailbox = account.mailbox()

inbox = mailbox.inbox_folder()
message = inbox.get_latest_message()

received_headers = message.headers['Received']

if 'TLS' in received_headers:
    print("The email is encrypted with TLS")
else:
    print("The email is not encrypted with TLS")

first you enter into your account, then you get get the latest email message in the inbox folder and finally check if the message has TLS encryption in transit

more about python-o365