Site icon Liam Cleary [MVP Alumni and MCT]

Sending Emails Using Microsoft Graph PowerShell

Recently Tobias Zimmergren posted a great article about sending emails using the Microsoft Graph with .NET. If you haven’t read it check it out now:

https://zimmergren.net/sending-e-mails-using-microsoft-graph-using-dotnet/

After reading it, I thought what might be interesting is doing the same thing but using the Microsoft Graph PowerShell commands instead.

So let’s get straight to it.

Step 1: Install and Import the PowerShell Module

Install-Module Microsoft.Graph
Import-Module Microsoft.Graph

Remember, you can choose to use either the production “v1.0” or “beta” endpoint.

Select-MgProfile -Name "beta"

Step 2: Connect to the Graph Using Required Permissions

Connect-MgGraph -Scopes `
		"Mail.Send"

Step 3: Download the Demonstration Email Template

Download the Email Templates from GitHub: https://github.com/ColorlibHQ/email-templates

It would help if you made any adjustments as required. For example, I created variables “{{NAME}},” “{{COMPANY}}” to replace with actual values when sending the mail.

Step 4: Create the PowerShell to Send the Email

Within the Graph PowerShell, we can use the command “Send-MgUserMail.” This command invokes the “sendMail” action within the core Graph API.

https://docs.microsoft.com/en-us/powershell/module/microsoft.graph.users.actions/send-mgusermail?view=graph-powershell-beta

$user = "admin@M365x.onmicrosoft.com"
$name = "Liam Cleary"
$company = "SharePlicity Education"
$subject = "SharePlicity Invitation"
$type = "html"

$template = Get-Content `
	-path "C:\PowerShell\Template\email\11\index.html" `
	-raw 

$template = $template.Replace('{{NAME}}',$name)
$template = $template.Replace('{{COMPANY}}',$company)
$content = $template

$recipients = @()
$recipients += @{
	emailAddress = @{
		address = $user
	}
}
$message = @{
	subject = $subject;
	toRecipients = $recipients;
	body = @{
		contentType = $type;
		content = $content
	}
}

Send-MgUserMail `
	-UserId $user `
	-Message $message

Of course, you can add further adjustments to the email format, the content, the recipients, etc.

It is always great to have different ways of achieving the same thing.

Exit mobile version