-
Notifications
You must be signed in to change notification settings - Fork 3
/
MgUserMail.ps1
83 lines (63 loc) · 2.34 KB
/
MgUserMail.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<#
Script for sending email with send-mgusermail
Ref:
https://mikecrowley.us/2021/10/27/sending-email-with-send-mgusermail-microsoft-graph-powershell
https://docs.microsoft.com/en-us/graph/api/user-sendmail
https://docs.microsoft.com/en-us/powershell/module/microsoft.graph.users.actions/send-mgusermail
#>
#region 1: Setup
$emailRecipients = @(
'user1@domain.com'
'user2@domain.biz'
)
$emailSender = 'me@domain.info'
$emailSubject = "Sample Email | " + (Get-Date -UFormat %e%b%Y)
$MgConnectParams = @{
ClientId = '<your app>'
TenantId = '<your tenant id>'
CertificateThumbprint = '<your thumbprint>'
}
Function ConvertTo-IMicrosoftGraphRecipient {
[cmdletbinding()]
Param(
[array]$SmtpAddresses
)
foreach ($address in $SmtpAddresses) {
@{
emailAddress = @{address = $address}
}
}
}
Function ConvertTo-IMicrosoftGraphAttachment {
[cmdletbinding()]
Param(
[string]$UploadDirectory
)
$directoryContents = Get-ChildItem $UploadDirectory -Attributes !Directory -Recurse
foreach ($file in $directoryContents) {
$encodedAttachment = [convert]::ToBase64String((Get-Content $file.FullName -Encoding byte))
@{
"@odata.type"= "#microsoft.graph.fileAttachment"
name = ($File.FullName -split '\\')[-1]
contentBytes = $encodedAttachment
}
}
}
#endregion 1
#region 2: Run
[array]$toRecipients = ConvertTo-IMicrosoftGraphRecipient -SmtpAddresses $emailRecipients
$attachments = ConvertTo-IMicrosoftGraphAttachment -UploadDirectory C:\tmp
$emailBody = @{
ContentType = 'html'
Content = Get-Content 'C:\tmp\HelloWorld.htm'
}
Connect-Graph @MgConnectParams
Select-MgProfile v1.0
$body += @{subject = $emailSubject}
$body += @{toRecipients = $toRecipients}
$body += @{attachments = $attachments}
$body += @{body = $emailBody}
$bodyParameter += @{'message' = $body}
$bodyParameter += @{'saveToSentItems' = $false}
Send-MgUserMail -UserId $emailSender -BodyParameter $bodyParameter
#endregion 2