Error adding link into email body

Thibeau, Chris 1 Reputation point
2022-04-08T15:23:54.777+00:00

Hi,

This should be simple but I'm stuck. Trying to use PowerShell with MS Graph to send mail with a link in the body.

$body = 
@"Hello World <a href = "https://microsoft.com">Microsoft</a>
@"

    $headers = @{
        "Authorization" = "Bearer $AccessTokenProd"
        "Content-type"  = "application/json"
    }
    $MailSender = "sender@example.com"

    $URLsend = "https://graph.microsoft.com/v1.0/users/$MailSender/sendMail"    

    $Body = 
    @"
        {
        "message" : {
        "subject": "Subject",
        "body" : {
        "contentType": "HTML",
        "content": "$Body"
        },
        "toRecipients": [
"@




    foreach ($ToAddress in $to) {
        $Body += 
        @"
{"emailAddress" : { "address" : "$ToAddress" }},
"@
    }

    $Body = $body.Remove($body.Length - 1, 1)
    $Body += "]}}"


    $Response = Invoke-RestMethod -Uri $URLsend -Headers $headers -Body $Body -Method Post

However, I get "Invoke-RestMethod : The remote server returned an error: (400) Bad Request" whenever quotes " are included in the body of the message.

How do you add an link <a href ="site">SIte Name</a> into the text body ?

I've also tried saving the body text as a file, then using get-content but this fails too.

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
11,099 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Thibeau, Chris 1 Reputation point
    2022-04-08T15:31:39.373+00:00

    figured it out, even though using Powershell the backtick character ` normally used to escape does not work.
    Need to use backslash \

    These do not work:

    $body = 
     @"Hello World <a href = "https://microsoft.com">Microsoft</a>
     @"
    
    $body = 
     @"Hello World <a href = `"https://microsoft.com`">Microsoft</a>
     @"
    

    This does:

    $body = 
     @"Hello World <a href = \"https://microsoft.com\">Microsoft</a>
     @"
    
    0 comments No comments