I am attempting to create an API in my Azure Static Web App which sends an email when a form submission occurs in my app.
I was able to get this working by passing a connection string to the EmailClient, but I would prefer to authenticate my EmailClient using Azure’s Service Principals as recommended in the email quickstart and briefly explained in the SMS quickstart.
I have tried passing an DefaultAzureCredential() as in the SMS quickstart
email_client = EmailClient(endpoint=endpoint, credential=DefaultAzureCredential())
But I get an error saying expected bytes or ASCII
in the credential parameter.
I then attempted to generate a token from the credential using the Client ID of the Email Communication Services object, so I could pass this as the credential per the identity docs, but I get an error saying that the scope has not been provided:
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
How do I authenticate the EmailClient using service principals? Or is this – as I suspect – a bug?
2
Answers
I tried in my environment and got below results:
Initially, I tried the EmailClient with Defaultcredentials and got same error:
TypeError: argument should be a bytes-like object or ASCII string, not ‘DefaultAzureCredential’
As a workaround for authentication to send an email using
EmailClient
I tried to useAzurekeycredential
method to send an email to the recipient.Code:
Console:
Mail:
The above code executed successfully by send mail to recipient with
Azurekeycredential
method.Reference:
Azure.communication.email.EmailClient class | Microsoft Learn
This is still in preview, so it’s not well documented. I can’t answer how to use the provided library, but here’s an example using the REST API with service principal authentication.
Note your principal needs the Contributor role on the Azure Communication Service as well