Skip to content

Instantly share code, notes, and snippets.

@memphisraynz
Created April 20, 2020 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save memphisraynz/6de692941d96b97e737325e22bc2458b to your computer and use it in GitHub Desktop.
Save memphisraynz/6de692941d96b97e737325e22bc2458b to your computer and use it in GitHub Desktop.
# Define AppId, secret and scope, your tenant name and endpoint URL
$ClientID = ''
$ClientSecret = ''
$tenantDomain = "domain.onmicrosoft.com"
$emailSender = "shared@domain.com"
$emailRecipient = $emailSender
$emailSubject = "Email sent via GraphAPI"
$emailBody = "<h1>Incoming Email</h1>`n"
$emailBody += "<p>Date: $(Get-Date)</p>`n"
$emailBody += "Email sent by GraphAPI"
$loginURL = "https://login.microsoft.com"
$resource = "https://graph.microsoft.com"
$body = @{grant_type="client_credentials";resource=$resource;client_id=$ClientID;client_secret=$ClientSecret}
$oauth = Invoke-RestMethod -Method Post -Uri $loginURL/$tenantdomain/oauth2/token?api-version=1.0 -Body $body
if ($null -ne $oauth.access_token) {
$reqBody='{
"message": {
"subject": "",
"body": {
"contentType": "",
"content": ""
},
"toRecipients": [
{
"emailAddress": {
"address": ""
}
}
]
}
}' | ConvertFrom-Json
$reqBody.message.subject = $emailSubject
$reqBody.message.body.contentType = "Html"
$reqBody.message.toRecipients.emailAddress.address = $emailRecipient
$reqBody.message.body.content = $emailBody
Invoke-RestMethod -Method Post -Uri "https://graph.microsoft.com/v1.0/users/$($emailSender)/sendMail" -Headers @{'Authorization'="$($oauth.token_type) $($oauth.access_token)"; 'Content-type'="application/json"} -Body ($reqBody | ConvertTo-Json -Depth 4 | Out-String)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment