如何通过Microsoft Graph API从Azure租户向外部收件人发送邮件?
问题
我需要以Microsoft Azure租户中Entra用户的身份发送邮件。目前使用Microsoft Graph API的https://graph.microsoft.com/v1.0/users/{user_id}/sendMail端点,发送给内部收件人时成功,但发送给外部收件人时出现404错误,错误信息如下:
TESTING EMAIL Failed to send email. Status code: 404, Response content: {"error":{"code":"ErrorInvalidUser","message":"The requested user 'recipient@example.com' is invalid."}}
请问是否支持向外部收件人发送邮件?若支持,正确的端点或方法是什么?
我的Python代码
def test_send_email(request): #DOCs #https://learn.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0&tabs=http print('TESTING EMAIL') client_id = settings.AZ_CLIENT_ID client_secret = settings.AZ_CLIENT_SECRET tenant_id = settings.AZ_TENANT_ID user_id = "Info@aztechcloud.co.uk" # Microsoft Graph API endpoint for sending emails graph_api_endpoint = 'https://graph.microsoft.com/v1.0/users/{user_id}/sendMail' recipient_email = 'me@example.com' # Obtain an access token using client credentials grant token_endpoint = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token' token_data = { 'grant_type': 'client_credentials', 'client_id': client_id, 'client_secret': client_secret, 'scope': 'https://graph.microsoft.com/.default', } token_response = requests.post(token_endpoint, data=token_data).json() access_token = token_response['access_token'] # Prepare the email data email_data = { 'message' : { 'subject': 'Test', 'body': { 'contentType': 'Text', 'content': 'This is a test', }, 'toRecipients': [ {'emailAddress': {'address': recipient_email}}, ], } } # Send the email using Microsoft Graph API headers = { 'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json', } response = requests.post(graph_api_endpoint.format(user_id=recipient_email), headers=headers, json=email_data) # Check the response if response.status_code == 201: print("Email sent successfully!") else: print(f"Failed to send email. Status code: {response.status_code}, Response content: {response.text}") return JsonResponse({"Success": "Email sent"}, status=200)
应用注册已配置Mail.Send的应用权限和委派权限。
解决方案
核心错误原因
你调用API时错误地将端点中的{user_id}替换成了外部收件人的邮箱,而这个位置必须填写租户内的合法Entra用户ID(可以是邮箱或对象ID),代表邮件的发送者。Graph API找不到这个外部用户,因此返回404错误。
正确操作步骤
- 修正端点参数:将
graph_api_endpoint.format(user_id=recipient_email)改为graph_api_endpoint.format(user_id=user_id),确保使用租户内的发送者身份(即你代码中定义的Info@aztechcloud.co.uk)。 - 确认权限有效性:你使用的是客户端凭证流(client_credentials),因此只有
Mail.Send的应用权限会生效,需确保该权限已被租户管理员同意。 - 外部收件人支持:
sendMail端点完全支持发送邮件给外部收件人,toRecipients字段直接填写外部邮箱地址即可。
修改后的关键代码行
# 使用发送者的user_id,而非收件人邮箱 response = requests.post(graph_api_endpoint.format(user_id=user_id), headers=headers, json=email_data)
补充说明
- 只要发送者是租户内合法用户,且应用拥有
Mail.Send应用权限,就能正常发送邮件给外部收件人。 - 委派权限仅在用户登录的授权流中生效,客户端凭证流不使用委派权限。
内容的提问来源于stack exchange,提问作者OptimusPrime
相关产品推荐
相关产品推荐

