How to Send Email from Azure with SendGrid, Graph and Office 365

choubertsprojects

VPN offers!

1. NordVPN

2. Surfshark

3. ExpressVPN

This blog post will show you how to send email from Azure with SendGrid, Graph and your Office 365 account. The use cases of this method are huge, but the end result is a nicely customized email that’s sent directly in seconds.

Azure SendGrid is a service that allows users to send email from Azure with SendGrid. It can be used for sending emails from Azure and it also works with Graph and Office 365.

How to Send Email from Azure with SendGrid, Graph and Office 365

There is no email delivery service provided by Microsoft Azure. Know that there is no native email service accessible in Azure, whether you’re testing apps or writing scripts to send emails.

In Azure, outbound SMTP connections through port 25 are also fully banned. If you’re an enterprise customer, you may request that your Azure tenant’s port 25 be unblocked. What other options do you have for sending emails from Azure?

SMTP smart hosts and REST API queries are the most common approaches to allow outgoing emails over Azure. Most email delivery platforms allow you to send emails using SMTP and API. You’ll discover how to send emails from Azure to the rest of the world in this post.

Prerequisites

There are several conditions you must satisfy if you wish to follow the examples as they develop in this tutorial.

Knowing Which Azure Email Services to Use When Sending Emails

There are a number of cloud email providers to choose from. SendGrid, MailJet, and MailGun are just a few of the well-known names. Using any email provider to send emails from Azure is the same; the SMTP server address and port, and the REST API endpoint address.

This article uses SendGrid as an example of a third-party email provider. Office 365 SMTP relay and Microsoft Graph API are two more email services used as examples.

Which Azure Email Service Should You Use in 2021?

Employing SendGrid

For sending emails from Azure, SendGrid is arguably the most common solution. Because Azure clients used to have a free plan with a monthly limit of 25,000 emails, SendGrid with Azure became quite popular.

Although the free plan is no longer available on the Azure interface, Microsoft verified that a free membership with a daily limit of 100 emails is still available. You may then send emails from an Azure app or VM using SendGrid’s SMTP relay service or Email API.

Getting Started with SendGrid

Employing SendGrid’s services requires you to have a SendGrid account first. Go to the Sign-up page, and you should see the form as shown below. Enter your email address and your chosen password. Then, accept the terms and click on the Create Account button.

Creating a SendGrid account for freeCreating a SendGrid account for free

You must provide your name and business details on the next page. You must also pick the necessary choices, such as your job, the number of workers, and the number of emails to send every month. Then press the Get Started button.

Filling up your account detailsFilling up your account details

You may see an error message reading, “You are not permitted to use SendGrid; please contact Support,” when you first log in to SendGrid. If this occurs, please contact SendGrid support. Before they unlock your account, they may need to ask you certain verification questions.

When you first log in, you’ll be prompted to activate Two-Factor Authentication. Make sure you follow the directions to the letter.

SendGrid Sender Identity Creation

Following the creation of the SendGrid account, the sender’s identity must be verified. You may either authenticate a single sender (for example, [email protected]) or an entire domain (e.g., domain.com).

You will construct a single sender identity that will function as your sender address in this example. SendGrid’s service will only allow messages to be sent from confirmed sender addresses. To establish a single sender identity, follow the steps below.

  1. Click the Create a Single Sender option on the Welcome page.

The creation of a single senderThe creation of a single sender

2. Fill out all of the relevant information on the Create a Sender fly-out. For easy reference, the mandatory fields are indicated with a red asterisk. Click Create after filling in the information.

Providing the sender's information Providing the sender’s information

The new sender address will then appear on the Single Sender Verification screen. The address is not yet validated, as displayed by a red X beneath the VERIFIED column in the sample below.

Viewing the status of sender address verificationViewing the status of sender address verification

3. Locate the email sent to the sender’s address, as shown in the image below, to verify the sender. After that, choose the Verify Single Sender option.

Verifying the address of the single sender Verifying the address of the single sender

The address of the sender will be confirmed. A screen similar to the one below should appear, verifying that the sender verification is complete.

Verifying that the sender address verification is finishedVerifying that the sender address verification is finished

How to Make a SendGrid API Key

The interface for generating API keys becomes accessible when the single sender address has been created. Consider the SendGrid API key to be your password. Your code will not be able to authenticate with the SendGrid SMTP relay service without it. To generate a new API key, follow the instructions below.

  1. On the left-hand side menu, click on Settings > API Keys. Then, click on the Create API Key button on the top-right corner of the page.

Creating a SendGrid API key for the first timeCreating a SendGrid API key for the first time

2. The Create API Key fly-out appears. Enter the name of the API key you are creating. Use a name that makes sense, such as “Azure Testing API Key.” Next, for simplicity’s sake, select Full Access as the permission. Finally, click on the Create & View button.

Choosing an API key name and permissionsChoosing an API key name and permissions

3. Next, the new API Key is shown. Because the key-value will not be displayed to you again, copy and save it now. After you’ve copied the key, click Done.

The new SendGrid API key is being saved.The new SendGrid API key is being saved.

Sending an Email from Azure Employing SendGrid SMTP Relay

You now have everything you need to utilize SendGrid to send Azure emails (account, sender, and key). It’s time to see whether the SendGrid SMTP relay service is up and running. You’ll use PowerShell to send emails from an Azure VM in this section.

You should be aware of these prerequisites before executing any code.

  • smtp.sendgrid.net is the SendGrid SMTP server address.
  • The apikey username is always used for SMTP authentication.
  • The value of the API key you established in SendGrid is the password to use.
  • Use port 25 instead. Instead, use port 587.
  • Only the SendGrid certified sender address may be used as the sender of your emails. The approved sender in this case is [email protected].

The script below uses the SendGrid SMTP relay to send an email. Change the $sendGridApiKey, From, To, and Body values in the code below. Then, in your PowerShell session, execute the code. To figure out what each line of code does, look at the comments.

# This is where you’ll enter your API key. ‘SG………..P258’ as $sendGridApiKey @ $SendGridEmail { # Make use of your confirmed sender address. ‘[email protected]’ as the sender # Choose an email recipient. Any working email address should suffice. ‘[email protected]’ as the recipient # Replace this with the topic of your email. ‘This is a test message from Azure sent using SendGrid.’ # Replace the body of the email with the message you wish to send. ‘This is a test message from Azure sent using SendGrid.’ # DO NOT EDIT ANYTHING BELOW THIS LINE. smtp.sendgrid.net = SmtpServer Port = 587 Credential = New-Object PSCredential ‘apikey’, (ConvertTo-SecureString $sendGridApiKey -AsPlainText -Force) UseSSL = $true Credential = New-Object PSCredential ‘apikey’, (ConvertTo-SecureStr # Send an email using the Send-MailMessage @SendGridEmail command.

The sample below illustrates what it looks like to execute the code above in PowerShell in real time.

Sending an Email from Azure Employing SendGrid SMTP RelaySending an Email from Azure Employing SendGrid SMTP Relay

Check the recipient’s inbox for the test message you sent to validate email deliverability. The end effect would look somewhat like this. As you can see, the message was sent using sendgrid.net from the sender’s address.

Confirming the delivery of the SMTP test messageConfirming the delivery of the SMTP test message

Send-MailMessage: The PowerShell Approach to Email

Sending an Email from Azure Employing SendGrid API

The SendGrid Web API V3 is another option to utilize SendGrid with Azure to deliver emails. Instead of utilizing SMTP to interact with SendGrid, the API makes use of HTTP. SendGrid’s API endpoint URL receives the HTTP request.

The Invoke-RestMethod cmdlet is used in the sample PowerShell script below to send the email request from Azure to SendGrid. Copy the code and alter the values of the variables $sendGridApiKey, $fromAddress, $toAddress, $mailSubject, and $mailMessage.

Run the code in PowerShell after you’ve finished modifying the variables.

Here you may enter your API Key. ‘SG………..P258’ as $sendGridApiKey Create a sender and recipient address. “[email protected]” as $fromAddress “[email protected]” as $toAddress Set the mail subject to “This is a test message from Azure through SendGrid API” $mailSubject Configure the email message $mailMessage = “This is a SendGrid API test message from Azure.” BELOW THIS LINE, DO NOT CHANGE ANYTHING. $mailbody = @personalizations = @(@ to = @(@ email = $toAddress) subject = $mailSubject) from = @(@ email = $fromAddress) content = @(@ type = “text/plain” value = $mailMessage) $headers = @ “Bearer $($sendGridApiKey)” is the authorization. ‘https://api.sendgrid.com/v3/mail/send’ as $mailApiUri Please send the email. -Method Invoke-RestMethod $mailApiUri -Body $mailbody -Headers $mailbody -ContentType application/json $headers

Check the recipient’s inbox after executing the PowerShell code above to make sure it got the test message. The sample below displays a test message from Azure that was successfully sent using the SendGrid API.

Verifying that the API test message was receivedVerifying that the API test message was received

Visit the V3 Mail Send API page to learn more about the SendGrid Web API.

SMTP Auth in Office 365

Another option to send Azure emails is to use the Office 365 SMTP relay. That is if your organization already has an Exchange Online subscription. Just like Employing SendGrid as an SMTP smart host, the Office 365 SMTP relay requires authentication and the use of port 587 only.

For Office 365 SMTP relay to operate, you must first understand the following prerequisites.

  • A genuine Exchange Online recipient object, such as a mailbox or a mail user, must be used as the sender address. Use a mailbox instead if you need to keep non-delivery receipts (NDR).
  • A valid Exchange Online license is required for the authenticating user. The Office 365 SMTP relay is only available to licensed Exchange Online subscribers.
  • Assume the authenticating user is not the same as the sender. In such instance, the sender account’s Send As permission must be provided to the user.
  • The authentication process is straightforward (legacy). SMTP Auth will no longer operate if SMTP basic authentication is removed in your business or when Microsoft ultimately disables basic authentication.
  • smtp.office365.com is the SMTP relay server address, and the port number is 587.

How to Send Email with PowerShell and Office 365 Direct Send

Creating a Sender Address in Office 365

The sender and authentication user are distinct in this case. First, make sure you’re connected to Exchange Online PowerShell. Follow the instructions below after you’ve connected.

Using the command below, create a shared mailbox. Replace the settings for -Name and -PrimarySMTPAddress with your own.

The shared mailbox should be created, and the outcome should look like this.

As the sender, create a new shared mailbox.As the sender, create a new shared mailbox.

The authenticated user should then be given the Send As privilege. The user is given the Send As access to the shared mailbox in the example below.

You should obtain a result similar to the one below after running the command above.

Send As permission is assigned.Send As permission is assigned.

Using Office 365 SMTP Relay to send an email from Azure

The next step is to test email delivery using PowerShell and Office 365 SMTP relay after creating the sender address and applying the Send As permission.

The code below uses [email protected] to authenticate. The sender is identified as [email protected]. Before executing the code, double-check that your settings are right.

# Enter your SMTP credentials here. ‘[email protected]’ as $username ‘*************’ as $password $fromAddress = ‘[email protected]’ # Provide the sender and recipient email addresses. ‘[email protected]’ as $toAddress # Fill in the email subject and message fields. ‘This is a test message from Azure through Office 365 SMTP Relay’, $mailSubject ‘This is a test message from Azure over the Office 365 SMTP Relay.’ # DO NOT EDIT ANYTHING BELOW THIS LINE. @$Office365RelayEmail = $Office365RelayEmail Subject = $mail From = $fromAddress To = $toAddress SmtpServer =’smtp.office365.com’ Subject Body = $mailMessage Port = 587 Credential = New-Object PSCredential $username, (ConvertTo-SecureString $password -AsPlainText -Force) UseSSL = $true Credential = New-Object PSCredential $username, (ConvertTo-SecureString # Make an email. @Office365RelayEmail Send-MailMessage

It is not advised to use plain text credentials in scripts. To protect usernames and passwords, production scripts must employ credential encryption or secret management.

It’s now time to check the mailbox of the receiver. Verify that the test message was successfully sent.

Confirming the delivery of the Office 365 SMTP relay test messageConfirming the delivery of the Office 365 SMTP relay test message

Sending Azure Email using the Microsoft Graph API

Instead of utilizing the Office 365 SMTP relay, utilize Microsoft Graph API, which is more secure and recommended. You may use REST API calls to send emails from any mailbox in your business using Microsoft Graph API.

A registered Azure AD app is required to utilize Microsoft Graph API to send emails. The Mail must be allocated to the registered app. Request API access. The parts that follow will walk you through configuring Microsoft Graph API and using it to send emails.

Using the Microsoft Graph API with PowerShell is related.

Adding a New Application to Azure Active Directory

You’ll register a new web app in the Azure active directory in this part. The new app serves as Microsoft Graph’s authenticating identity. If you haven’t already, log in to the Azure Portal.

  1. Navigate to Azure Active Directory —> App registration. Then, click on the New registration button.

Creating a fresh registration for an appCreating a fresh registration for an app

2. Enter the app’s name on the Register an application page.

3. Select Accounts in this organizational directory only under Supported account types. As the Redirect URI, use HTTP://localhost. After that, press the Register button.

Application registrationApplication registration

4. Wait for the registration process to be finished. It simply takes a few seconds to complete the procedure. Remember to write down the Application (client) ID and Directory (tenant) ID values. Those will come in handy later.

The Application ID and Directory values are saved.The Application ID and Directory values are saved.

Making a Secret Key for a Client

Consider the username to be the application ID you generated in the previous step. That application ID, in turn, requires a password – the secret key.

Follow the procedures below to add a new application secret key.

  1. Go to Certificates & secrets, then click on New client secret.
  2. Enter the client secret’s description, such as key1.
  3. Select the expiration date for the secret and click Add. The secret key in the example below will expire in one year.

Adding a new secret key for a clientAdding a new secret key for a client

The new key will be listed in the Client secrets section. You’ll only see the key value once, so make a duplicate now.

Viewing the value of the client's secret keyViewing the value of the client’s secret key

Giving admin permission and Assigning API Permission

It’s time to give the needed Microsoft Graph API access now that you’ve generated the application ID and secret. The program may authenticate without authorization, but it won’t be able to do anything else, like send emails.

Follow the steps below to begin allocating permission.

  1. On the left-hand menu, choose API permissions.

2. Next, click the Add a permission button on the Configured permissions page.

Adding API authorizationAdding API authorization

3. Select Microsoft Graph API from the Request API permissions fly-out.

Choosing the Microsoft Graph APIChoosing the Microsoft Graph API

4. When prompted, choose Program permissions as the kind of access requested by the application.

5. Type Mail into the search box. Send it to be looked for. To check your mail, click the result. Please send permission. Finally, choose Add permissions.

Giving permission to mail.sendGiving permission to mail.send

6. You’ll notice that the permission status is “Not granted for <organization name>.” At this point, you or a Global admin must first give consent for the application. To grant permission, click on the Grant admin consent for <organization> button.

Giving admin permissionGiving admin permission

The API permission status then changes to “Granted for <organization name>”.

Obtaining confirmation of API permissionsObtaining confirmation of API permissions

Getting a Token of Access

An access token is required for requests submitted to the Microsoft Graph API. You already have your application ID, secret key, and tenant ID at this stage. To get an access token, you’ll need those three pieces of information.

The access token request is sent to the Microsoft Graph API endpoint using the PowerShell script below. You must first change the values of $client id, $client secret, and $tenant id to your desired values. Then, in PowerShell, copy and paste the code to request the access token.

# Replace your application ID with yours. $application id = $client id # substitute your secret key ‘SECRET KEY’ as $client secret # update your tenant ID with yours ‘TENANT ID’ as $tenant id BELOW THIS LINE, DO NOT CHANGE ANYTHING. @method = ‘POST’ URI = $request “body = @ grant type = “client credentials” scope = “https://graph.microsoft.com/.default” https://login.microsoftonline.com/$tenant id/oauth2/v2.0/token “client secret = $client secret client id = $client id # Obtain an access token. (Invoke-RestMethod @request) $token # acces token look at the token’s value $token

The PowerShell script above is shown in the video below. The requested access token is saved in the $token field, as you can see.

Obtaining an access tokenObtaining an access token

Access tokens are only good for one hour from the moment of purchase. After the old access token has expired, you must obtain a new one.

Using the Microsoft Graph API to send an email from Azure

You may now send emails using the Microsoft Graph API with Azure. This time, you’ll use the access token you got in the previous phase to generate an email request.

The script below creates a plain-text message containing the essential elements of sender, receiver, topic, and content. Change the values of $fromAddress, $toAddress, $mailSubject, and $mailMessage as necessary. Then paste the code into PowerShell and execute it.

# Include both the sender and recipient’s email addresses. $toAddress = ‘RECIPIENT ADDRESS HERE’ $fromAddress = ‘SENDER ADDRESS HERE’ # Fill in the email subject and message fields. ‘This is a test message from Azure through Microsoft Graph API’ $mailSubject = ‘This is a test message from Azure via Microsoft Graph API’ $mailMessage = ‘This is a test message from Azure via Microsoft Graph API’ # DO NOT EDIT BELOW THIS LINE. # Create a request for the Microsoft Graph API. @”URI” = “https://graph.microsoft.com/v1.0/users/$fromAddress/sendMail” $params = @ “URI” = “https://graph.microsoft.com/v1.0/users/ “Authorization” = (“Bearer 0” -F $token) “Headers” = @ “POST” = “Method” “Body” = (@ “message” = @ “subject” = $mail) “ContentType” = “application/json” Subject “body” = @ “contentType” = ‘Text’ “content” = $mailMessage “toRecipients” = @(@ “emailAddress” = @ “address” = $toAddress ) # Transmit the message @params -Verbose Invoke-RestMethod

What occurs when you execute the PowerShell script above is shown in the video below.

Using the Microsoft Graph API to send an emailUsing the Microsoft Graph API to send an email

Finally, look for the email in your recipient’s inbox to confirm delivery. You should see something similar to the picture below.

Confirming the delivery of the Microsoft Graph API test messageConfirming the delivery of the Microsoft Graph API test message

How to Use PowerShell to Send Email Securely

Steps to Follow

The lack of an Azure email delivery service should not be a deal breaker. Administrators and developers may still use Azure to send emails using code. SMTP relay and email API integration are available from third-party email providers.

If you already have an Office 365 subscription, you may additionally use the Office 365 SMTP relay and the Microsoft Graph API.

Try MailJet, MailGun, SocketLabs, and SendInBlue, which were not included in this post. Try them out with Azure Automation Runbooks and Azure Web Apps as well!

The “azure send email notification” is a process that allows users to send email from Azure. SendGrid, Graph, and Office 365 all have their own ways of doing this, but the end result is the same.

Related Tags

  • sending email from azure using office 365
  • send email from azure web app
  • how to send email using sendgrid with azure
  • azure sendgrid smtp relay
  • azure simple email service