Sending SMTP email with Microsoft Graph and OAUTH authentication using VB.net
Elie El Karkafi
Microsoft MVP | MCT | Senior Solutions Architect at ampiO Solutions
Sending emails from custom application and integrations in Azure is relatively easy. In this post, we will check out a use case we had with one of our customers for an easy way to setup the basic configuration and code for allowing a custom developed application to send emails with Microsoft Graph and OAUTH authentication using VB.net
Whether you are building a fully customized app, low app code, or integrations using existing plus and play solutions, Microsoft always recommends you to use a third party or a SendGrid, for sending emails in Azure. This is the way forward to do it but sometimes its not !
However, before we dive deeper into the config and the code. Let's look when this solution match the business requirements in some situtations.
Sometimes, you may like to send an e-mail and keep the history of the entire conversation at your fingertips - in your Microsoft 365 mailbox. Using the Microsoft Graph APIs to send e-mails as a user, you can decide whether to keep the sent e-mails in your "Sent" folder. This setup helps a lot with conversations that have sparked from your automated e-mails. For me, this creates a seamless experience.
Simply, it's your code, so you set the rules. Logically integrate the e-mail solution you build into your existing applications and workflows, allowing a fully customized experience.
Sometimes, working with these requirements can be challenging.?Using the Microsoft Graph APIs allows you to use the service and mailbox accounts already part of and approved by your organization.
Setup
To allow our applications to send e-mails as a given user or service account, we need to configure an Azure AD application with the appropriate permission. Additionally, we need to ensure that the user or service account has a license assigned for sending e-mails.
The process of configuring our Azure AD apps and users is very straightforward.
Create an Azure AD App with Graph permissions
To allow our app to send e-mails using our user or service account, we need to configure an Azure AD application with the appropriate permissions.
Create a new App Registration
Head over to Azure AD and create a new App Registration.
Click on Register
Set up the application permissions
From the test app page in the Azure Portal navigate to:
Your configured permissions should look like this :
Using a Client ID and Client Secret
We need to create a new secret and securely store the value of the said secret, along with the Tenant ID and the app's Client ID
领英推荐
From the App page navigate to:
Next, make sure you copy the Application ID (Client ID) and the Tenant ID for your application. You can find these on the Overview page of your app.
To recap, you should at this point have stored these values for use later in our code:
Ensure your user or service account has a license to send e-mails
Go to the Azure Portal:
We are done with the preparations. At this point, we should have:
The Code
Install the required dependencies
To allow successful communication with Microsoft Graph, we need to make use of a few NuGet libraries.
We use the?Azure.Identity?to retrieve our?ClientSecretCredential?object, and we use the?Microsoft.Graph?to instantiate a new?GraphServiceClient?and eventually, send e-mails with the?Users.SendMail?endpoint.
Here's the VB.net code
Replace the tenantID with the Tenant ID, replace the clientID with the Application ID, replace the secret from the step above.
Replace the UPN on this line 'await graphClient.Users["[email protected]"]' with a user that has a mailbox in your tenant.
I am using Visual Studio with VB.net to write my code.
Public Shared Async Sub SendEmail(
??? Dim scopes = {"https://graph.microsoft.com/.default"}
??? Dim tenantId = "1f63282c-f731-4437-8d64-f8180fbb4676"?????????? ' Replace with your Tenant ID
??? Dim clientId = "r1ct9e4e-5a26-4073-ac9c-fd07744c5fcy"?????????? ' Replace with Application ID from Overview tab
??? Dim clientSecret = "8tK2Q~DmhAz.IGbgcIVN.vcTIVRNYMW3672f45dlJ"? ' Replace with the Client Secret
?
??? ' Using Azure.Identity;
??? Dim options = New TokenCredentialOptions With {
??????? .AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
??? }
?
??? Dim clientSecretCredential = New ClientSecretCredential(tenantId, clientId, clientSecret, options)
??? Dim graphClient As GraphServiceClient = New GraphServiceClient(clientSecretCredential, scopes)
?
??? Dim message = New Microsoft.Graph.Message() With {
??????? .Subject = "This is the subject line",
??????? .Body = New ItemBody With {
??????????? .ContentType = BodyType.Text,
??????????? .Content = "This is the body of the email message."
??????? },
??????? .ToRecipients = New List(Of Recipient)() From {
??????????? New Recipient With {
??????????????? .EmailAddress = New EmailAddress With {
??????????????????? .Address = "[email protected]"????? ' This is the recipient of the message
??????????????? }
??????????? }
??????? }
??? }
?
??? ' Specify the user account to send from. An account in your tenant. It also sends the email.
??? Await graphClient.Users("[email protected]").SendMail(message, Nothing).Request().PostAsync()
End Sub)
That's it !
Your custom application is now ready to send emails in Azure with Microsoft Graph and OAUTH Authentication using VB.net.
Solutions Architect (Cloud & IoT) at Atos
1 年???????? Ready to embrace your Microsoft Certification journey? www.edusum.com/microsoft offers the perfect study companion for your success. #CertificationGoals #Edusum ????
Digital Transformation Leader | Solutions Architect | Senior Software Engineer
1 年Good, very good! But I need send email with attachments, how could I ?
Analista Programmatore
1 年Great job, thanks
Azure Solution Architect | ITIL | Azure DevOps | IaC | O365 | Terraform
2 年good work