Microsoft Graph is a must-have toolset you have to know and use when dealing with the Microsoft Cloud. Recently Microsoft added a Powershell wrapper around the the Graph-API, the MS Graph PowerShell SDK, which is available on the PowerShell Gallery with 49(!) modules.
The documentation around the PowerShell-Modules has still „room for improvement“, if you really want to get usable functionality, it still necessary to read the API documentation or leverage graph explorer, and read blogs from Techguy Michael Seidl here or Tony Redmond here.
All i wanted was to send a simple e-mail with MS-Graph using the PowerShell Commandlets, and this is the result to reproduce for you.
Step 1: Install necessary PowerShell Modules
To start, we need three modules out of all the MS-Graph Modules, which are installed with these commands:
1 2 3 |
Install-Module Microsoft.Graph.Authentication -Scope CurrentUser Install-Module Microsoft.Graph.Mail -Scope CurrentUser Install-Module Microsoft.Graph.Users.Actions -Scope CurrentUser |
Step 2: Connect to your O365/M365 tenant
So first lets connect to our tenant. Run the three lines below and connect to your M365 tenant via browser-login. You will get asked to give the account to use the permissions to use MS-Graph. (PS: This is not my real TenantID)
1 2 3 4 |
$TenantId = 'e6c62eca-31a7-40a3-a3c4-cdbd4fc74464' Connect-MgGraph -TenantId $tenantId -Scope "Mail.Send, Mail.ReadWrite" $Details = Get-MgContext $Details |
Step 3 : Craft and send an E-Mail
It was a little bit tricky to figure out what kind of sata has to be passed to the commandlet parameters, and there is much more you can do (attachments, HTML cormatting, …) but we can start with this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#region craftig an e-mail $SendingDateTime = "{0:G}" -f (Get-Date) $MessageBody = @{ content = "This Mail is sent via MSGraph Comandlets at $sendingDateTime" contentType = 'HTML' } $MailSender = $details.Account $recipient = @{ emailAddress = @{ address = 'somename@maildomain.com' } } #endregion #region Sending the e-mail $NewMessage = New-MguserMessage -UserId $Mailsender -Body $MessageBody -ToRecipients $recipient -Subject 'MS Graph Testmail' Send-MgUserMessage -UserId $MailSender -Messageid $newmessage.id #endregion |
For explanaition on the above code:
The $messagebody is a simple text with a timestamp in it for reference on sending time. The $recipient list MUST be a hashtable inside a hastable.
Then just create the message with New-MgUserMessage and send it with Send-MgUserMessage. the result should be something just like in the header screenshot.
Thats it – have fun with the „Mg“-Commandlets.
Roman