You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Azure AD应用实现邮件自动化及解决发送邮件时的403错误

Troubleshooting 403 Error & Permission Questions for Azure AD App Email Sending

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.Send permissions 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=data in the token request, which sets invalid headers (requests automatically handles the correct content-type when using the data parameter)
  • 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

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:

  1. Connect to Exchange Online PowerShell:

    Connect-ExchangeOnline -UserPrincipalName your_admin_account@your_tenant.com
    
  2. Create 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)
  3. 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.
  4. Verify the policy:

    Test-ApplicationAccessPolicy -AppId <your_app_client_id> -Identity <target_mailbox_email>
    
    • If the policy works, it will return Allowed for mailboxes in the group and Denied for others.

内容的提问来源于stack exchange,提问作者Tanmaya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 19:22:41