Search code examples
azureazure-devopsoauth-2.0azure-devops-rest-api

Azure Devops REST API SendMail


I'm trying to send mail after the successful stage on my release definition. Following the docs OAuth box is checked in my stage Project Collection Service Account is added to Build Administrators and Release Administrators.

But the response from REST API is "Azure DevOps Login Page" Here is my script:

$OrganizationName = "myorg"
$ProjectName = "myproj"
$sendmailto = "[email protected]"
$mysubject = "Test Mail Subjcet"
$mailbody = "Mail body to test it works with azure rest api" 
$PAT="MYPAT"
$Token = "$(System.AccessToken)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$Token"))

$HeaderMail = @{
    Authorization = "Bearer $encodedCreds"
}


##send mail
$urimail = "https://${OrganizationName}.vsrm.visualstudio.com/${ProjectName}/_apis/Release/sendmail/$($env:RELEASE_RELEASEID)?api-version=3.2-preview.1"
$requestBody =
@"
{
"senderType":1,
"to":{"tfsIds":[$sendmailto]},
"body":"${mailbody}",
"subject":"${mysubject}"
}
"@
Try {
Invoke-RestMethod -Uri $urimail -Body $requestBody -Method POST -ContentType "application/json" -Headers $HeaderMail
}
Catch {
$_.Exception
}

Tested with: Tried with 3.2 version and 7.1

PAT Token and authorization to Basic return 400 with Bearer return 401.

Switch $(System.AccessToken) to $($env:System_AccessToken) trygin to convert to base64 and without.

What I'm missing?

Response from ConsoleLog


Solution

  • It's caused by the $requestBody. The request body requires valid Azure DevOps users referenced by their tfsIds.

    Below PS script works for me, if your are running it in pipeline, then please use the $(System.AccessToken) instead of $PAT.

    Running locally and authenticate with PAT:

    $OrganizationName = "organization"
    $ProjectName = "Project"
    $sendmailto = "[email protected]"
    $mysubject = "Test Mail Subjcet"
    $PAT="xxx"
    $encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$PAT"))
    
    $HeaderMail = @{
        Authorization = "Basic $encodedCreds"
    }
    
    #Get the tfsid
    
    $userentitlementurl = "https://vsaex.dev.azure.com/${OrganizationName}/_apis/userentitlements?api-version=7.1-preview.1"
    
    $response = Invoke-RestMethod -Uri $userentitlementurl -Method Get -Headers $HeaderMail
    
    #Filter by sendmailto
    $tfsid = ($response.value| where {$_.user.mailAddress -eq $sendmailto}).id
    
    Write-Host $tfsid
    
    ##send mail
    $urimail = "https://vsrm.dev.azure.com/${OrganizationName}/${ProjectName}/_apis/Release/sendmail/168?api-version=7.1-preview.1"
    $requestBody =
    @"
    {
        "senderType": 1,
        "to": {
            "tfsIds": [
                "$tfsid"
            ],
            "emailAddresses": []
        },
        "subject": "$mysubject",
        "sections": [
            5,
            0,
            1,
            2,
            4
        ]
    }
    "@
    Try {
    Invoke-RestMethod -Uri $urimail -Body $requestBody -Method POST -ContentType "application/json" -Headers $HeaderMail
    }
    Catch {
    $_.Exception
    }
    

    enter image description here

    Running in release pipeline and authenticate with $(System.AccessToken): (Please note that, because this script is being run during the release, the summary email will show the environment as IN PROGRESS even if it is run as the last step in the Release.)

    $OrganizationName = "organization"
    $ProjectName = "project"
    $sendmailto = "[email protected]"
    $mysubject = "Test Mail Subjcet"
    
    $HeaderMail = @{
        Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
    }
     
    #Get the tfsid
    
    $userentitlementurl = "https://vsaex.dev.azure.com/${OrganizationName}/_apis/userentitlements?api-version=7.1-preview.1"
    
    $response = Invoke-RestMethod -Uri $userentitlementurl -Method Get -Headers $HeaderMail
    
    #Filter by sendmailto
    $tfsid = ($response.value| where {$_.user.mailAddress -eq $sendmailto}).id
    
    Write-Host $tfsid
    
    ##send mail
    $urimail = "$env:SYSTEM_TEAMFOUNDATIONSERVERURI$env:SYSTEM_TEAMPROJECT/_apis/Release/sendmail/$($env:RELEASE_RELEASEID)?api-version=7.1-preview.1"
    
    $requestBody =
    @"
    {
        "senderType": 1,
        "to": {
            "tfsIds": [
                "$tfsid"
            ],
            "emailAddresses": []
        },
        "subject": "$mysubject",
        "sections": [
            5,
            0,
            1,
            2,
            4
        ]
    }
    "@
    Try {
    Invoke-RestMethod -Uri $urimail -Body $requestBody -Method POST -ContentType "application/json" -Headers $HeaderMail
    }
    Catch {
    $_.Exception
    }
    

    enter image description here