Send HTML Email using Microsoft Graph SDK

 

We were in a situation where we want to send the email from one of the automations without using our on-premises relay.

I was recently exploring Microsoft Graph SDK because of the future retirement for MSOL and AZUREAD modules.

Its not just a module but it is a utilities box for Microsoft cloud eco system, every time I work on it, I found something new

and interesting, I have found few bugs as well which I will share in some blog post.

Let’s install the Microsoft Graph SDK before we get into sending Email from it.

 

Install-Module Microsoft.Graph

 

I am not going in details on how to connect it first time and admin consent requirement but straight getting into how to use it.

As I am using this inside the script, so I am using certificate-based authentication for its connection.

 

Connect-MgGraph -ClientId $ClientID -CertificateThumbprint $ThumbPrint -TenantId $TenantName

 

Here is the example on how to Send HTML email using it.

APP you have registered for it should have Mail.Send permissions.

 


Call your HTML file using get content in the $body variable.

 


 

$body = Get-Content “.\htmlfile.htm” -raw #get the HTML File as raw

$Subject = “HTML Report file”

$from = “DoNotReply@techwizard.cloud”

$recipients = @();$recipients += @{emailAddress = @{address = “VSukhija@techwizard.cloud “}}

$bccrecipients=@();$bccrecipients += @{emailAddress = @{address = “Reports@ techwizard.cloud”}}

$message = @{subject = $subject;toRecipients = $recipients;BccRecipients = $bccrecipients;body = @{contentType = “html”;content = $body}} # form the message


Send-MgUserMail -UserId $from -Message $message # Send message sing Graph SDK

 

You can disconnect from Graph if your script is completed.

Disconnect-MgGraph

 

Here is the HTML email received:

I hope this small code sample will be helpful to you in case you are also wondering on how to send HTML email using GRAPH.

 

Thanks for reading …

Tech Wizard

https://techwizard.cloud

https://syscloudpro.com/

PowerShell Fast Track

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s