Sending emails from Azure is a recurrent task for sysadmins or developers. To send email, there are many options, you can use SendGrid which is a great service for sending emails from Azure, you can use Graph API which is the option I will describe in this article. In next months, you will be able to use Azure communication service, which is still in public preview, so not ready for production.
What is interesting with this option is that you don’t need to use login/password in your script or code. With Graph API, you can send emails from any mailbox in your organization using REST API calls.
Getting started
First, we need a new app registration to authenticate against Azure AD. Go to the Azure Portal, Azure Active Directory section, then App registrations:
Click New registration to create a new one.
Enter the name of the application and select “Single tenant”:
After registering the new app registration, copy the following value:
We will need these values later in our PowerShell code. Next, we need to create a new application secret key, go to Certificates & secrets and click New client secret
Enter the description and select when the secret will expire (recommended is 6 months).
Don’t forget to note the value, you will need it later.
Now we need to assign permission to this application in order to send email. Without permissions, the application can only authenticate but will not be able to send emails.
Go to the API permissions tab, and click Add a permission
Select Microsoft Graph and click Application permissions
In the search box, type in Mail.Send. Select the Mail.Send permission.
To grant permission, click on the Grant admin consent button.
Now, we can use our Azure App to send a test email.
Requests sent to Microsoft Graph API require an access token that you must generate. More information can be found here: https://learn.microsoft.com/en-us/graph/auth/auth-concepts
After generating the access token, you can use the following code. Below is a PowerShell code to send an email using Azure App. Replace the variables:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# Variables $fromAddress = 'Update_the_value' $toAddress = 'Update_the_value' $mailSubject = 'This is a test message' $mailMessage = 'This is a test message' # Graph API Request $params = @{ "URI" = "https://graph.microsoft.com/v1.0/users/$fromAddress/sendMail" "Headers" = @{ "Authorization" = ("Bearer {0}" -F $token) } "Method" = "POST" "ContentType" = 'application/json' "Body" = (@{ "message" = @{ "subject" = $mailSubject "body" = @{ "contentType" = 'Text' "content" = $mailMessage } "toRecipients" = @( @{ "emailAddress" = @{ "address" = $toAddress } } ) } }) | ConvertTo-JSON -Depth 10 } # Send the message Invoke-RestMethod @params -Verbose |