[英]Authenticate Azure Email Communication Services using Service Principals in Python
我正在尝试在我的 Azure Static Web 应用程序中创建一个 API,当我的应用程序中发生表单提交时,它会发送一个 email。
我能够通过将连接字符串传递给 EmailClient 来实现此功能,但我更愿意按照 email 快速入门中的建议并在SMS 快速入门中简要说明,使用 Azure 的服务主体对我的EmailClient进行身份验证。
我试过像 SMS 快速入门中那样传递 DefaultAzureCredential()
email_client = EmailClient(endpoint=endpoint, credential=DefaultAzureCredential())
但是我收到一条错误消息,指出凭证参数中的expected bytes or ASCII
。
然后,我尝试使用 Email 通信服务 object 的客户端 ID 从凭据生成令牌,因此我可以根据身份文档将其作为凭据传递,但我收到一条错误消息,指出尚未提供 scope:
credential=DefaultAzureCredential()
token=credential.get_token(scopes="bbjkl-xyz-abc/.default").token
email_client = EmailClient(endpoint=endpoint, credential=token)
DefaultAzureCredential failed to retrieve a token from the included credentials.
Attempted credentials:
EnvironmentCredential: "get_token" requires at least one scope
如何使用服务主体对 EmailClient 进行身份验证? 或者这是 - 正如我怀疑的那样 - 一个错误?
我在我的环境中尝试并得到以下结果:
最初,我尝试使用 Defaultcredentials 的 EmailClient 并得到同样的错误:
TypeError:参数应该是类似字节的 object 或 ASCII 字符串,而不是“DefaultAzureCredential”
作为使用EmailClient
发送 email 的身份验证解决方法,我尝试使用Azurekeycredential
方法向收件人发送 email。
代码:
from azure.communication.email import EmailClient,EmailAddress,EmailContent,EmailRecipients,EmailMessage
from azure.core.credentials import AzureKeyCredential
end="< your communication endpoint >"
cred=AzureKeyCredential(key="< key of azure communication service >")
email=EmailClient(endpoint=end,credential=cred)
content = EmailContent(
subject="Welcome to Azure Communication Services Email",
plain_text="This email message is sent from Azure Communication Services Email using the Python SDK.",
)
address = EmailAddress(email="demomail.com")
recipient = EmailRecipients(to=[address])
message = EmailMessage(
sender="DoNotReply@xxxxxxxxxx.azurecomm.net",
content=content,
recipients=recipient
)
response = email.send(message)
安慰:
邮件:上面的代码通过使用Azurekeycredential
方法向收件人发送邮件成功执行。
参考:
这仍处于预览阶段,因此没有很好的记录。 我无法回答如何使用提供的库,但这里有一个使用 REST API 和服务主体身份验证的示例。
请注意,您的委托人还需要Azure 通信服务的贡献者角色
import msal
import requests
import uuid
from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime
def get_token_with_client_secret(client_id, client_secret, tenant_id):
app = msal.ConfidentialClientApplication(
client_id = client_id,
client_credential = client_secret,
authority = f"https://login.microsoftonline.com/{tenant_id}")
scopes = ["https://communication.azure.com/.default"]
token = app.acquire_token_for_client(scopes = scopes)
return(token)
def main():
tenant_id = ""
client_id = ""
client_secret = ""
endpoint = "https://endpoint.communication.azure.com/"
sender = "DoNotReply@guid.azurecomm.net"
# Obtain a token using the application credentials
cred = get_token_with_client_secret(client_id, client_secret, tenant_id)
# Generate timestamp to use in the repeatability-first-sent header
now = datetime.now()
stamp = mktime(now.timetuple())
time = format_date_time(stamp)
request_url = f"{endpoint}emails:send?api-version=2021-10-01-preview"
request_headers = {
"Authorization": "Bearer " + cred["access_token"],
"Content-Type": "application/json",
"repeatability-request-id": str(uuid.uuid4()),
"repeatability-first-sent": time
}
request_body = {
"Sender": sender,
"Content": {
"Subject": "Email Subject",
"PlainText": "This is the email body"
},
"Importance": "Normal",
"Recipients": {
"To": [
{
"Email": "user@company.com",
"DisplayName": "User"
}
]
}
}
response = requests.post(url = request_url, headers = request_headers, json = request_body)
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.