To generate credentials for accessing specific users' emails via IMAP, you'll need to set up an Azure AD application with the correct permissions and user restrictions. Here's how to do it properly:
- Register an Application in Azure AD
- Go to Azure Portal → Azure Active Directory → App registrations → New registration
- Create a new application (e.g., "Email Access App")
- Kindly note the Application (client) ID and Directory (tenant) ID
Find documentation: https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-register-app?tabs=certificate%2Cexpose-a-web-api
- Configure API Permissions
- Under your app → API permissions → Add a permission
- Select Microsoft Graph → Delegated permissions
- Add:
- Mail.Read (to read emails)
- IMAP.AccessAsUser.All (for IMAP access)
- User.Read (basic profile access)
Find: https://learn.microsoft.com/en-us/graph/permissions-reference#mail-permissions
- Create a Client Secret
Under your app → Certificates & secrets → New client secret
Set expiration period (recommend 12-24 months for production)
Copy the secret value (only visible once)
- Restrict Access to Specific Users
Under your app → Authentication
- Set "Supported account types" to "Accounts in this organizational directory only."
Under "Advanced settings" → Allow public client flows → Set to "No"
- Implement User Assignment (This is optional but recommended)
Under your app → Properties
Set "Assignment required?" to Yes
Go to "Users and groups" → Add user/group → Select specific users
To access emails via IMAP, use the OAuth 2.0 authorization code flow to get access tokens for each user:
from msal import PublicClientApplication
import requests
app = PublicClientApplication(
"your-client-id",
authority="https://login.microsoftonline.com/your-tenant-id"
)
result = app.acquire_token_interactive(scopes=["https://outlook.office.com/IMAP.AccessAsUser.All"])
# Use the token for IMAP access
imap_token = result["access_token"]
Important Security Considerations:
- Least privilege: Only request permissions you need.
- Secret rotation: Implement a process to regularly rotate client secrets.
- Audit logs: Monitor usage in Azure AD → Monitoring → Sign-in logs.
- Conditional Access: Consider adding CA policies for extra protection.
- Admin consent: You may need admin consent for some permissions.
Alternative Approach;
Instead of client secrets, consider using:
- Certificate-based authentication (more secure than client secrets)
- Managed identities (if running in Azure)
- Device code flow (for user-specific access without storing secrets)
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
Regards,
Obinna