I have a webapp built using flask.
Now, I have a requirement which needs me to expand a distribution list. I came across exchangelib library and tried using it.
I'm able to configure without any issue. I'm using OAuth2. I also have an app registered on Azure.
The exchangelib configuration is :
from exchangelib import OAuth2Credentials,Version,Build,Configuration,Account,Credentials,IMPERSONATION,OAUTH2
from exchangelib.version import EXCHANGE_O365
username = '<primary_smtp_email_id>'
tenant_id = app.config['APP_TENANT_ID']
client_id = app.config['APP_CLIENT_ID']
secret_value = app.config['APP_CLIENT_SECRET']
version=Version(build=EXCHANGE_O365)
credentials = OAuth2Credentials(client_id=client_id, client_secret=secret_value, tenant_id=tenant_id)
config = Configuration(service_endpoint = 'https://outlook.office365.com/EWS/Exchange.asmx',
credentials=credentials,
auth_type=OAUTH2 ,
version=version)
account = Account(username, credentials=credentials, autodiscover=False, config=config, access_type=IMPERSONATION)
And the code to expand a DL :
def print_expanded_dl(dl):
for mailbox in account.protocol.expand_dl(dl):
print(mailbox.email_address)
But, I'm getting an error when I call the print_expanded_dl function. The error that i am encountering is :
exchangelib.errors.ErrorInvalidExchangeImpersonationHeaderData: ExchangeImpersonation SOAP header must be present for this type of OAuth token.
Kindly help since I searched for similar cases and found that the access_type in configuration needs to be set to IMPERSONATION. I have already done it. Also, The app on Azure has the following permissions :
Also, If there is any other way to expand a distribution list using some other library, Feel free to suggest the same. Thank you.

You need to also set the
identityattribute on yourCredentialsinstance, as described in https://ecederstrand.github.io/exchangelib/#oauth-authentication