我希望能够以 Entra 中存在的用户身份在我们的 Microsoft Azure 租户上发送帐户。
我正在尝试使用图形 API 端点“https://graph.microsoft.com/v1.0/users/{user_id}/sendMail”。
我可以发送给内部收件人,但不能发送给外部收件人。尝试外部时,我收到以下错误:
测试电子邮件 发送电子邮件失败。状态码:404,响应 内容:{“error”:{“code”:“ErrorInvalidUser”,“message”:“请求的内容 用户“[电子邮件受保护]”无效。”}}
是否可以使用 Microsoft 作为提供商发送给外部收件人?如果是这样,正确的终点或方法是什么?
这是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 = "[email protected]"
# Microsoft Graph API endpoint for sending emails
graph_api_endpoint = 'https://graph.microsoft.com/v1.0/users/{user_id}/sendMail'
recipient_email = '[email protected]'
# 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 权限。
在 MS Azure 平台中,您应该使用 SendGrid 服务来生成短信/电子邮件通知并将其发送给内部/外部邮件收件人。
SendGrid 是一项付费服务,但在企业级应用程序中非常有用。 SendGrid 还提供单独的门户,通过易于使用的分析来监控电子邮件统计数据和其他传送报告。