Search code examples
pythonsmtpexchangelib

Exchangelib read emails from a service account without personal login


I would like to read the inbox of a shared service account. The service account inbox is a shared inbox and does not have a password per-se. I can log in and read my personal inbox using this:

from exchangelib import DELEGATE, Account, Credentials
import pytz
from datetime import datetime, date, time
now = datetime.now() # current date and time
timestr = now.strftime("%m-%d-%Y, %H.%M.%S")

credentials = Credentials(
    username='[email protected]',
    password='Password1'
)
a = Account(
    primary_smtp_address='[email protected]',
    credentials=credentials,
    autodiscover=True,
    access_type=DELEGATE
)
print('im in')
key = 'Filter Word'
midnight = datetime.combine(datetime.today(), time.min, pytz.UTC)
for item in a.inbox.filter(datetime_received__gte=midnight, subject__icontains=key).order_by('-datetime_received')[
            :30]:
    print(item.subject)

I think the answer to my question lies somewhere in the credentials portion. I have been able to read the shared inbox by using my personal credentials and inputting the inbox address in the primary_smtp_address field. Like this:

    credentials = Credentials(
    username='[email protected]',
    password='Password1'
)
a = Account(
    primary_smtp_address='[email protected]',
    credentials=credentials,
    autodiscover=True,
    access_type=DELEGATE
)

This works great, however, if (for some reason) my credentials no longer become valid at the company, I would like the script to still run. Is there a way to do this?


Solution

  • If you don't want to access the shared account using a personal account, you should create a service account in Exchange and use that to login instead.

    You cannot access the shared account without some sort of authentication.