如何配置Azure AD应用实现邮件自动化及解决发送邮件时的403错误
Hey there! Let's break down your 403 error and permission concerns one by one.
First: Fixing the 403 Forbidden Error
Your 403 issue is likely a mix of incorrect permission types and a small code bug. Here's what to do:
1. Correct the API Permissions in Azure AD
You're using the client credentials flow (grant_type=client_credentials), which requires application permissions (not delegated permissions). Right now, most of the permissions you added are delegated (designed for user-interactive scenarios).
- Go to your Azure AD app registration > API Permissions
- Remove any delegated
Mail.Sendpermissions you have - Click Add a permission > Microsoft Graph > Application permissions
- Search for and add
Mail.Send(application-level permission) - Click Grant admin consent for [your tenant] to activate this permission
2. Fix the Code Issues
Your code has two key problems that are causing the 403 (or invalid token):
- You're passing
headers=datain the token request, which sets invalid headers (requests automatically handles the correct content-type when using thedataparameter) - The JSON body has unnecessary escaped quotes (
\") which will cause parsing errors
Here's the corrected code with comments:
import requests import json import urllib3 def ebiw_check() -> None: """ Checks EBIW Application access and sends email. """ try: # Token request payload token_data = { 'tenant': 'your_tenant_id', 'client_id': 'your_client_id', 'client_secret': 'your_client_secret', 'grant_type': 'client_credentials', 'scope': 'https://graph.microsoft.com/.default' } # Fetch access token (removed invalid headers=data parameter) token_url = "https://login.microsoftonline.com/your_tenant_id/oauth2/v2.0/token" token_response = requests.post(token_url, data=token_data, timeout=60).json() if "access_token" not in token_response: print(f"Failed to get token: {token_response}") return print("Token fetched Successfully") # Send email via Graph API send_mail_url = 'https://graph.microsoft.com/v1.0/users/sender_mail_id/sendmail' mail_body = { "message": { "subject": "Meet for meeting?", "body": { "contentType": "Text", "content": "The new cafeteria is open." }, "toRecipients": [ { "emailAddress": { "address": "recipient_email_id" } } ], }, "saveToSentItems": "true" } request_headers = { "Authorization": f"Bearer {token_response['access_token']}", 'Content-Type': "application/json" } # Disable SSL warnings only for testing (remove in production) urllib3.disable_warnings() mail_response = requests.post( send_mail_url, data=json.dumps(mail_body), timeout=20, headers=request_headers, verify=False ) # Print detailed response for debugging print(f"Response Status: {mail_response.status_code}") print(f"Response Content: {mail_response.text}") except Exception as e: print(f"Error occurred: {str(e)}") ebiw_check()
Second: Your Permission Questions
Q1: Does an app with admin consent have access to all mailboxes in the organization?
Yes, when you grant an application permission (like Mail.Send) with admin consent, the app has access to all mailboxes in your tenant by default (for the scope of that permission).
Q2: Can I restrict the app to only specific mailboxes?
Absolutely! You can use Application Access Policies to limit the app's access to a specific set of mailboxes. Here's how to do it via Exchange Online PowerShell:
Connect to Exchange Online PowerShell:
Connect-ExchangeOnline -UserPrincipalName your_admin_account@your_tenant.comCreate a mail-enabled security group:
- Add all the mailboxes you want the app to access to this group (you can do this in Azure AD or Exchange Admin Center)
Create the application access policy:
New-ApplicationAccessPolicy -AppId <your_app_client_id> -PolicyScopeGroupId <security_group_email_address> -AccessRight RestrictAccess -Description "Restrict app to specific mailboxes"- This policy tells the app it can only access mailboxes in the specified security group.
Verify the policy:
Test-ApplicationAccessPolicy -AppId <your_app_client_id> -Identity <target_mailbox_email>- If the policy works, it will return
Allowedfor mailboxes in the group andDeniedfor others.
- If the policy works, it will return
内容的提问来源于stack exchange,提问作者Tanmaya

