How can I add email recipients to a Graph API request programmatically?

I have some runbooks running in Azure Automation. I am adding email notifications to the runbooks. I’ve configured a simple runbook to send emails. Rather than adding an email “section” to the end of each runbook, I would like to have a single “email” runbook that can be called from the other runbooks. I’ve run into a problem with the number of email recipients. How can I dynamically change the number of email recipients in the Graph API request to match the number of recipients that would be passed from the other runbook?

Here’s the email runbook. It works great as written.

# Import variables from Azure Automation account
$client_id = Get-AutomationVariable -Name 'Azure Automation Emails Application Client ID'
$client_key = Get-AutomationVariable -Name 'Azure Automation Emails Application Key'
$tenant_id = Get-AutomationVariable -Name 'Azure Automation Emails Application Tenant ID'

# Get an access token to send the email
$request = @{
    Method = 'POST'
    URI    = "https://login.microsoftonline.com/$tenant_id/oauth2/v2.0/token"
    body   = @{
        grant_type    = "client_credentials"
        scope         = "https://graph.microsoft.com/.default"
        client_id     = $client_id
        client_secret = $client_key
    }
}
$token = (Invoke-RestMethod @request).access_token
# DEBUGGING - view the token value
#$token

# Provide the sender and recipient email addresses
$fromAddress = '[email protected]'
$toAddress1 = '[email protected]'
$toAddress2 = '[email protected]'

# Specify the email subject and the message
$mailSubject = 'Test email'
$mailMessage = 'this is a test'

# Build the Graph API request and send the message
$params = @{
    "URI"         = "https://graph.microsoft.com/v1.0/users/$fromAddress/sendMail"
    "Headers"     = @{
      "Authorization" = ("Bearer {0}" -F $token)
    }
    "Method"      = "POST"
    "ContentType" = 'application/json'
    "Body" = (@{
        "message" = @{
            "subject" = $mailSubject
            "body"    = @{
                "contentType" = 'Text'
                "content"     = $mailMessage
            }
            "toRecipients" = @(
                @{
                    "emailAddress" = @{
                        "address" = $toAddress1
                    }
                }
                @{
                    "emailAddress" = @{
                        "address" = $toAddress2
                    }
                }
            )
        }
    }) | ConvertTo-JSON -Depth 10
  }
  # Send the message
  Invoke-RestMethod @params -Verbose

The email runbook will fail if I null or blank $toAddress2, or if I have anything other than a valid email address. I’ve tried converting $toAddress1 to an array, like so, $toAddress1 = @{"address" = "[email protected]"; "address" = "[email protected]"}, but that fails because you cannot have duplicate keys in an array.

Or is the best option to simply build the Graph API request params at the end of each runbook, then pass that as a variable to the email runbook?

You can use a single array and then have a loop in the toRecipients property to dynamically handle the recipients:

$toAddress = '[email protected]', '[email protected]'

if ($toAddress.Count -eq 0) {
    # you should exit early here since there are no recipients
    throw 'No rescipients...'
}

$params = @{
    URI         = "https://graph.microsoft.com/v1.0/users/$fromAddress/sendMail"
    Headers     = @{
        Authorization = 'Bearer {0}' -f $token
    }
    Method      = 'POST'
    ContentType = 'application/json'
    Body        = @{
        message = @{
            subject      = $mailSubject
            body         = @{
                contentType = 'Text'
                content     = $mailMessage
            }
            toRecipients = @(
                # here you can add a loop to create a new hashtable
                # per recipient in `$toAddress`
                $toAddress | ForEach-Object {
                    @{
                        emailAddress = @{
                            address = $_
                        }
                    }
                }
            )
        }
    } | ConvertTo-Json -Depth 10
}

You could also set up input parameters in your runbook instead of hardcoding the recipients, so you can pass them in when calling your runbook:

param([Parameter(Mandatory)] [string[]] $Recipients)

$params = @{
    URI         = "https://graph.microsoft.com/v1.0/users/$fromAddress/sendMail"
    Headers     = @{
        Authorization = 'Bearer {0}' -f $token
    }
    Method      = 'POST'
    ContentType = 'application/json'
    Body        = @{
        message = @{
            subject      = $mailSubject
            body         = @{
                contentType = 'Text'
                content     = $mailMessage
            }
            toRecipients = @(
                $Recipients | ForEach-Object {
                    @{
                        emailAddress = @{
                            address = $_
                        }
                    }
                }
            )
        }
    } | ConvertTo-Json -Depth 10
}

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật