I need to know user emails and id (so I can identify the user from the email).
According to Microsoft documentation, the below code should allow the retrival of user information.
import asyncio
import configparser
from azure.identity.aio import ClientSecretCredential
from msgraph import GraphServiceClient
from msgraph.generated.users.item.user_item_request_builder import UserItemRequestBuilder
def main():
# Load settings
config = configparser.ConfigParser()
config.read(['config.cfg', 'config.dev.cfg'])
azure_settings = config['azure']
credentials = ClientSecretCredential(
azure_settings['tenantId'],
azure_settings['clientId'],
azure_settings['clientSecret'],
)
scopes = ['https://graph.microsoft.com/.default']
client = GraphServiceClient(credentials=credentials, scopes=scopes)
query_params = UserItemRequestBuilder.UserItemRequestBuilderGetQueryParameters(select=['id', 'mail', ])
request_config = UserItemRequestBuilder.UserItemRequestBuilderGetRequestConfiguration(query_parameters=query_params)
users = asyncio.run(client.users.get(request_config))
print(users)
However, I get the error
Traceback (most recent call last):
File "C:\Users\PycharmProjects\ProcessEmailReceipts\microsoft_graph.py", line 35, in <module>
main()
File "C:\Users\PycharmProjects\ProcessEmailReceipts\microsoft_graph.py", line 28, in main
request_config = UserItemRequestBuilder.UserItemRequestBuilderGetRequestConfiguration(query_parameters=query_params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: type object 'UserItemRequestBuilder' has no attribute 'UserItemRequestBuilderGetRequestConfiguration'
Looking at the repo, that class does indeed not exists.
Is there a way to get all users id and emails with the python sdk?
Thanks,
Initially, register one Entra ID application and grant User.Read.All
permission of Application type as below:
To get all the users with ID and Emails using MS Graph Python SDK, make use of below sample code:
import asyncio
from azure.identity import ClientSecretCredential
from msgraph import GraphServiceClient
tenant_id = "tenantID"
client_id = "appID"
client_secret = "secret"
credential = ClientSecretCredential(
tenant_id=tenant_id,
client_id=client_id,
client_secret=client_secret
)
client = GraphServiceClient(credential)
async def main():
result = await client.users.get()
users = result.value
for user in users:
print("User ID:", user.id)
print("User Email:", user.mail)
print("User Display Name:", user.display_name)
print("-" * 50) # Separating each user with a line
asyncio.run(main())
Response:
Reference: