Sending email though powershell with Microsoft Graph

Calvin Quint 0 Reputation points
2023-08-03T21:32:07.1033333+00:00

I am using the following powershell script to test the functionality of email notification using Microsoft Graph. The emai script sends the email but in the inbox of the receiver I am getting a failed delivery.

# Configuration
$clientId = " "          # Replace with your client ID from Azure Portal
$clientSecret = "xR58Q~kFupQw97inkyh9el62elMHzKIBhOBcubqj"  # Replace with your client secret from Azure Portal
$tenantId = " "          # Replace with your tenant ID
$recipientEmail = " "  # Replace with the recipient's email address
$fromEmail = " " # Replace with the email address sending the email

# Function to get access token using v2 endpoint
function Get-AccessToken {
    param (
        [string]$clientId,
        [string]$clientSecret,
        [string]$tenantId
    )

    $tokenEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
    $body = @{
        grant_type    = "client_credentials"
        client_id     = $clientId
        client_secret = $clientSecret
        scope         = "https://graph.microsoft.com/.default"
    }

    $response = Invoke-RestMethod -Uri $tokenEndpoint -Method Post -Body $body
    return $response.access_token
}

# Function to send email using Microsoft Graph API
function Send-Email {
    param (
        [string]$accessToken,
        [string]$recipientEmail,
        [string]$subject,
        [string]$body,
        [string]$fromEmail
    )

    $graphApiEndpoint = "https://graph.microsoft.com/v1.0/users/$($recipientEmail)/sendMail"
    $headers = @{
        Authorization = "Bearer $accessToken"
        "Content-Type" = "application/json"
    }

    $emailData = @{
        message = @{
            subject = $subject
            body = @{
                contentType = "Text"
                content = $body
            }
            toRecipients = @(
                @{
                    emailAddress = @{
                        address = $recipientEmail
                    }
                }
            )
            from = @{
                emailAddress = @{
                    address = $fromEmail
                }
            }
        }
    }

    $emailJson = $emailData | ConvertTo-Json -Depth 100
    Invoke-RestMethod -Uri $graphApiEndpoint -Method Post -Headers $headers -Body $emailJson -ContentType "application/json"
}

# Main script
try {
    # Get the access token
    $accessToken = Get-AccessToken -clientId $clientId -clientSecret $clientSecret -tenantId $tenantId

    # Compose the email subject and body
    $subject = "Test Email from PowerShell"
    $body = "This is a test email sent from PowerShell using Microsoft Graph API."
    $sender = "Sender Name <$fromEmail>"

    # Send the email
    Send-Email -accessToken $accessToken -recipientEmail $recipientEmail -subject $subject -body $body -fromEmail $sender

    Write-Host "Email sent successfully!"
}
catch {
    Write-Host "Failed to send email: $($_.Exception.Message)"
}

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
12,305 questions
Exchange Server Development
Exchange Server Development
Exchange Server: A family of Microsoft client/server messaging and collaboration software.Development: The process of researching, productizing, and refining new or existing technologies.
549 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,608 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Justin Workman 0 Reputation points
    2023-10-30T16:19:50.09+00:00

    In the URL for $graphApiEndpoint in the Send-Email function, the $recipientEmail is present. This should be the sender address.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.