gpt4 book ai didi

python - 使用 Python 中的服务主体对 Azure 电子邮件通信服务进行身份验证

转载 作者:行者123 更新时间:2023-12-03 06:31:05 28 4
gpt4 key购买 nike

我正在尝试在我的 Azure 静态 Web 应用程序中创建一个 API,当我的应用程序中发生表单提交时,该 API 会发送电子邮件。

我可以通过将连接字符串传递给 EmailClient 来实现此功能,但我更愿意验证我的 EmailClient按照 the email quickstart 中的建议使用 Azure 的服务主体并在the SMS quickstart中进行了简要解释.

我已尝试按照 SMS 快速入门中的方式传递 DefaultAzureCredential()

email_client = EmailClient(endpoint=endpoint, credential=DefaultAzureCredential())

但我收到一条错误消息,提示凭据参数中存在expected bytes or ASCII

然后,我尝试使用电子邮件通信服务对象的客户端 ID 从凭证生成 token ,因此我可以将其作为凭证传递给 the identity docs ,但我收到一条错误消息,指出尚未提供范围:

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 并得到了相同的错误:

enter image description here

类型错误:参数应该是类似字节的对象或 ASCII 字符串,而不是“DefaultAzureCredential”

作为使用 EmailClient 进行身份验证发送电子邮件的解决方法,我尝试使用 Azurekeycredential 方法发送给收件人的电子邮件。

代码:

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="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d09220322391f283d21340d35353535353535353535632c37383f282e22202063232839" rel="noreferrer noopener nofollow">[email protected]</a>",
content=content,
recipients=recipient
)

response = email.send(message)

控制台:

enter image description here

邮件:通过使用 Azurekeycredential 方法向收件人发送邮件,上述代码已成功执行。

enter image description here

引用:

Azure.communication.email.EmailClient class | Microsoft Learn

关于python - 使用 Python 中的服务主体对 Azure 电子邮件通信服务进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75230352/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com