How to Send Emails Using Microsoft Graph PowerShell

Legacy email authentication methods are becoming a thing of the past, with legacy authentication for Exchange Online now dead and 3rd party services becoming increasingly hard to protect, especially while needing to add them as trusted sources of mail for your domain, an alternative method of programmatically sending emails is essential. 

The Send-MgUserMail cmdlet in Microsoft Graph PowerShell provides a convenient and easy way to send emails programmatically using PowerShell in both interactive and non-interactive PowerShell sessions. 

In this tutorial, I am going to show you how to use Microsoft Graph PowerShell and Graph API to programmatically send emails using your existing Exchange Online service. 

Removing the need for 3rd party services

With legacy authentication for Exchange Online now unusable, other methods of relaying email securely have been a constant need for many organisations. While demanding applications (such as Microsoft Dynamics) or behind-the-curve devices (such as MFPs) can easily use methods such as Office 365 Direct Send (providing they are behind a static public IP) or utilise existing hybrid infrastructure (if you are unfortunate enough to still have it…), programmatic solutions have been a challenge, especially while using services such as Azure Automation and trying to prevent the use of 3rd party infrastructure.

Third-party services such as SMTP2Go or SendGrid can seem like attractive options to resolve this issue, but there lies the question:

  • Should you rotate the passwords?
  • How secure are they really?
  • Are they compliant?
  • How do I track and monitor for vulnerabilities?
  • The list goes on…

To simple answer to this problem is to not use them at all and instead use what is readily available to you, the Graph API with PowerShell!

About Send-MgUserMail

The Send-MgUserMail cmdlet can be found in the Microsoft.Graph.Users.Actions module of the Microsoft Graph PowerShell SDK and the command can be utilised with both delegate and application permissions in different contexts. 

To use the cmdlet you need to consent to the mail.send permission scope, but depending if you consent to this permission using delegated or application permissions, a different level of access is granted. 

If you consent to the mail.send permission in a delegated scenario, you may notice you can only send mail as the user authenticated in your current session (the current user context).

Send mail as you
Send mail as you

However, when consenting to the equivalent application permission, you will notice you can send mail as any user in your organisation.

Mail.Send application permission
Mail.Send application permission

As you can see, mail.send is a dangerously powerful permission and should be used with care. If you plan on using this permission with Azure Automation, consider using Managed Identities to remove the need to manage client secrets or certificates and keep your environment secure.

Send Emails with Microsoft Graph PowerShell

Send an email with delegated permissions

To send emails with delegated permissions under your own user context, you need to connect to Microsoft Graph with the Connect-MgGraph cmdlet and the Mail.Send permission scope:

Connect-MgGraph -scope Mail.Send

Then, the actual mail message needs to be defined as a hashtable, here is a simple example to send a basic text-based email from a specific address. Be sure to change the ‘YOUR EMAIL HERE’ text with the email of the account you used to authenticate to Microsoft Graph.

$body = @{
	message = @{
		subject = "My Microsoft Graph Test Email"
		body = @{
			contentType = "Text"
			content = "Hello, this is a test email"
		}
		toRecipients = @(
			@{
				emailAddress = @{
					address = "YOUR EMAIL HERE"
				}
			}
		)
	}
	saveToSentItems = "false"
}

Lastly, to send the email, use the Send-MgUserMail cmdlet as follows:

Send-MgUserMail -UserId %YourUPN% -BodyParameter $body

Send an email with application permissions

As we already know, application permissions expose more power when defining the Mail.Send permission. This means we can be more flexible with our script.

Start by connecting to Microsoft Graph. If you are not already familiar with how to do this, follow my guide here: How to Connect to Microsoft Graph PowerShell With a Client Secret.

A slightly different approach can be taken when using application permissions, like my example below. Here you can see I have added the -to and -from parameters to my script, which allows the user to define to who and from who the email will be sent.  The value of these parameters can also be obtained from other sources if the to/from address depends on the result of an automatic action, such as if you are using Azure Automation.

Param(
    [Parameter(Mandatory)]
    [ValidateNotNull()]
    [mailaddress]
    ${to},

    [Parameter(Mandatory)]
    [ValidateNotNull()]
    [mailaddress]
    ${from}
)

$ApplicationId = "APPID"
$SecuredPassword = "SECRETKEY"
$tenantID = "TENANTID"
$SecuredPasswordPassword = ConvertTo-SecureString -String $SecuredPassword -AsPlainText -Force
$ClientSecretCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ApplicationId, $SecuredPasswordPassword
Connect-MgGraph -TenantId $tenantID -ClientSecretCredential $ClientSecretCredential

$body = @{
	message = @{
		subject = "My Microsoft Graph Test Email"
		body = @{
			contentType = "Text"
			content = "Hello, this is a test email"
		}
		toRecipients = @(
			@{
				emailAddress = @{
					address = "$to"
				}
			}
		)
	}
	saveToSentItems = "false"
}

Send-MgUserMail -UserId $from -BodyParameter $body

Modify message headers with Send-MgUserMail

Message headers contain important information about the source of an email and any email servers that the message passed through. Administrators like us can then use the information in the message header to determine specifics about an email for troubleshooting. For more detailed information about message headers, see my tutorial: Review and Interpret Message Headers in Exchange Online.

In our case, we can add additional information to a message sent using the Send-MgUserMail cmdlet to help other users determine the source of the email and other troubleshooting factors. Another good reason you may want to do this is so you can apply or exclude specific Exchange transport rules to these messages, for example, you may exclude these messages for any journalling rules.

To do this, you need to add the following code within the message = @{} hashtable:

InternetMessageHeaders = @(
			@{
				Name = "x-custom-header-name"
				Value = "custom value"
			}
		)

You can also add multiple headers to your message by duplicating the hashtable within:

InternetMessageHeaders = @(
			@{
				Name = "x-custom-header-name"
				Value = "custom value"
			}
			@{
				Name = "x-custom-header-name2"
				Value = "custom value2"
			}	
		)

Modify the x-custom-header-name (while ensuring the header starts with x-) to something more specific along with the custom value. Below you can see an example of my message so far:

$body = @{
	message = @{
		subject = "My Microsoft Graph Test Email"
		body = @{
			contentType = "Text"
			content = "Hello, this is a test email"
		}
		toRecipients = @(
			@{
				emailAddress = @{
					address = "[email protected]"
				}
			}
		)
       	InternetMessageHeaders = @(
			@{
				Name = "x-ocn-header-source"
				Value = "azure-automation"
			}
		)
	}
	saveToSentItems = "false"
}

Once you have created your header, send a test email and view the message header properties. If you are using OWA, you can right-click on the message, then click View > View message details.

Custom header added
Custom header added

Send attachments with Microsoft Graph PowerShell

Attachments can contain important information for the recipient, so it is useful to learn how to add attachments to emails while sending emails programmatically.

Attachments can be added from various sources while using PowerShell, for example:

  • Downloaded from the internet using Invoke-WebRequest
  • Manually selected using file explorer in Windows
  • Generated within PowerShell itself

While manually selecting a file is useful during interactive PowerShell sessions, non-interactive sessions will require you to handle attachment adding automatically. Let’s look at how to add attachments both manually and automatically.

Manually selecting attachments

Existing attachments can be manually defined in your code to be used in email messages. You can do this by defining the path of your file, converting it to a base 64 string and including it in your message body.

To retrieve the attachment you can use the following example and change the file path C:\temp\MyTextFile.txt.

$Attachment = "C:\temp\MyTextFile.txt"
$MailAttachement = [Convert]::ToBase64String([IO.File]::ReadAllBytes($Attachment))

Then define the attachments within the message@{} hashtable.

  attachments = @(
			@{
				"@odata.type" = "#microsoft.graph.fileAttachment"
				name = "$Attachment"
				contentType = "text/plain"
				contentBytes = $MailAttachement
			}
    )

The full body hashtable should now look like the following:

$body = @{
	message = @{
		subject = "My Microsoft Graph Test Email"
		body = @{
			contentType = "Text"
			content = "Hello, this is a test email"
		}
		toRecipients = @(
			@{
				emailAddress = @{
					address = "[email protected]"
				}
			}
		)
        attachments = @(
			@{
				"@odata.type" = "#microsoft.graph.fileAttachment"
				name = "$Attachment"
				contentType = "text/plain"
				contentBytes = $MailAttachement
			}
        )
	}
	saveToSentItems = "false"
}

Downloading attachments online

A more convenient place to store files is on a central GitHub repository. Of course, if you are making documents public, they should only be basic template files or functional scripts (which include no company or identifiable data, otherwise, an access token is needed to access a private repository.

The following example uses the Invoke-WebRequest cmdlet to download a file from a public GitHub repository and prepare it to be attached to a message.

$attachment = Invoke-WebRequest -Uri "https://raw.githubusercontent.com/DanielBradley1/Public/main/Testing/MyTestCSVFile.csv"
$encodedBytes = [System.Text.Encoding]::UTF8.GetBytes($attachment.Content)
$MailAttachment = [System.Convert]::ToBase64String($encodedBytes)

You may also want to define the attachment name dynamically, in which case you can use Regex to select the file name after the last forward slash in the file path. For example:

$attachment.BaseResponse.ResponseUri.AbsolutePath -match '([^\/]+$)'
$matches[1]

The full code will look like the following:

$attachment = Invoke-WebRequest -Uri "https://raw.githubusercontent.com/DanielBradley1/Public/main/Testing/MyTestTextFile.txt"
$encodedBytes = [System.Text.Encoding]::UTF8.GetBytes($attachment.Content)
$MailAttachment = [System.Convert]::ToBase64String($encodedBytes)
$attachment.BaseResponse.ResponseUri.AbsolutePath -match '([^\/]+$)'
$matches[1]

$params = @{
	message = @{
		subject = "Automated - Inactive User Report"
		body = @{
			contentType = "Text"
			content = "Please see the attached!"
		}
		toRecipients = @(
			@{
				emailAddress = @{
					address = "[email protected]"
				}
			}
		)
    attachments = @(
			@{
				"@odata.type" = "#microsoft.graph.fileAttachment"
				name = $matches[1]
				contentType = "text/plain"
				contentBytes = $MailAttachment
			}
    )
	}
	saveToSentItems = "false"
    
}

Building attachments with PowerShell objects

More commonly, you are likely to be creating reports using PowerShell and then sending that data attached to an email. A simple way of doing this is to build a fixed array of data, then convert that to an HTML report and attaching to your email. 

Let’s say you already have your array of data, a good example to use is my inactive user report script here: https://ourcloudnetwork.com/create-an-inactive-m365-user-report-with-microsoft-graph-powershell/.

To attach the $report array that was built with our script to an email, you can use the below example to convert it to HTML format, apply a border to tidy up the table then prepare it to be attached to the email.

$report = $report | ConvertTo-Html
$Report = $report -replace '<table>', '<table border="1">'
$encodedBytes = [System.Text.Encoding]::UTF8.GetBytes($report)
$MailAttachment = [System.Convert]::ToBase64String($encodedBytes)

The file can then be attached to the email in the same manner as the previous examples.

All email options for Send-MgUserMail

Fundamentally, there are many other variations of message properties that can be sent using Microsoft Graph. To find out more information on the properties of a message you can customise, check out the message resource type documentation from the Microsoft Graph Docs: https://learn.microsoft.com/en-us/graph/api/resources/message?view=graph-rest-beta

If you are having any trouble with adding further properties, comment below and I will be happy to assist asap.

Daniel Bradley

Daniel Bradley is a UK-based technical architect and Microsoft MVP in Security. He specialises in Microsoft Entra, Intune, and Microsoft Graph PowerShell and is the author of Microsoft Graph PowerShell for Administrators. He writes and edits Our Cloud Network using experience gained from working with Microsoft cloud environments.

This Post Has 2 Comments

  1. Ron Boyd

    HI Daniel
    I am not an Email programmer, but a pretty good monkey see – monkey do kind of programmer

    I cannot find a Powershell script to send an email using MS Graph and a company logo in the body. It seems MS Graph only does text messages

    1. Hey Ron,

      You can send HTML in the body of an email with MS Graph, then you can design the email how you like!

      Hope that helps 🙂

Leave a Reply