您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

从 Runbook 发送电子邮件Send an email from a runbook

可以使用 PowerShell 通过 SendGrid 从 runbook 发送电子邮件。You can send an email from a runbook with SendGrid using PowerShell.

先决条件Prerequisites

创建 Azure Key VaultCreate an Azure Key Vault

可以使用以下 PowerShell 脚本创建 Azure Key Vault。You can create an Azure Key Vault using the following PowerShell script. 将变量值替换为特定于环境的值。Replace the variable values with values specific to your environment. 单击代码块右上角的试运行按钮,使用嵌入的 Azure Cloud Shell。Use the embedded Azure Cloud Shell via the Try It button, located in the top right corner of the code block. 也可复制代码并在本地运行它,前提是已在本地计算机上安装 Az 模块You can also copy and run the code locally if you have the Az modules installed on your local machine.

备注

若要检索 API 密钥,请使用查找 SendGrid API 密钥中的步骤。To retrieve your API key, use the steps in Find your SendGrid API key.

$SubscriptionId  =  "<subscription ID>"

# Sign in to your Azure account and select your subscription
# If you omit the SubscriptionId parameter, the default subscription is selected.
Connect-AzAccount -SubscriptionId $SubscriptionId

# Use Get-AzLocation to see your available locations.
$region = "southcentralus"
$KeyVaultResourceGroupName  = "mykeyvaultgroup"
$VaultName = "<Enter a universally unique vault name>"
$SendGridAPIKey = "<SendGrid API key>"
$AutomationAccountName = "testaa"

# Create new Resource Group, or omit this step if you already have a resource group.
New-AzResourceGroup -Name $KeyVaultResourceGroupName -Location $region

# Create the new key vault
$newKeyVault = New-AzKeyVault -VaultName $VaultName -ResourceGroupName $KeyVaultResourceGroupName -Location $region
$resourceId = $newKeyVault.ResourceId

# Convert the SendGrid API key into a SecureString
$Secret = ConvertTo-SecureString -String $SendGridAPIKey -AsPlainText -Force
Set-AzKeyVaultSecret -VaultName $VaultName -Name 'SendGridAPIKey' -SecretValue $Secret

# Grant access to the Key Vault to the Automation Run As account.
$connection = Get-AzAutomationConnection -ResourceGroupName $KeyVaultResourceGroupName -AutomationAccountName $AutomationAccountName -Name AzureRunAsConnection
$appID = $connection.FieldDefinitionValues.ApplicationId
Set-AzKeyVaultAccessPolicy -VaultName $VaultName -ServicePrincipalName $appID -PermissionsToSecrets Set, Get

若要通过其他方式创建 Azure 密钥保管库并存储机密,请参阅密钥保管库快速入门For other ways to create an Azure Key Vault and store a secret, see Key Vault quickstarts.

将所需模块导入自动化帐户Import required modules into your Automation account

若要在 runbook 中使用 Azure 密钥保管库,必须将以下模块导入到自动化帐户中:To use Azure Key Vault within a runbook, you must import the following modules into your Automation account:

有关说明,请参阅导入 Az 模块For instructions, see Import Az modules.

创建用于发送电子邮件的 runbookCreate the runbook to send an email

在创建密钥保管库并存储 SendGrid API 密钥后,即可创建 runbook 来检索 API 密钥和发送电子邮件。After you have created a Key Vault and stored your SendGrid API key, it's time to create the runbook that retrieves the API key and sends an email. 让我们使用 runbook,该 runbook 使用 AzureRunAsConnection运行方式帐户身份向 Azure 进行身份验证,以便从 Azure 密钥保管库检索机密。Let's use a runbook that uses AzureRunAsConnection as a Run As account to authenticate with Azure to retrieve the secret from Azure Key Vault. 我们将该 runbook 命名为 Send-GridMailMessage。We'll call the runbook Send-GridMailMessage. 你可以修改用作示例的 PowerShell 脚本,并将其重用于不同的方案。You can modify the PowerShell script used for example purposes, and reuse it for different scenarios.

  1. 转到 Azure 自动化帐户。Go to your Azure Automation account.

  2. 在“过程自动化”下,选择“Runbook”。 Under Process Automation, select Runbooks.

  3. 在 Runbook 列表的顶部选择“+ 创建 Runbook”。At the top of the list of runbooks, select + Create a runbook.

  4. 在“添加 Runbook”页上,输入 Send-GridMailMessage 作为 runbook 名称。On the Add Runbook page, enter Send-GridMailMessage for the runbook name. 对于 runbook 类型,选择“PowerShell”。For the runbook type, select PowerShell. 然后选择“创建”。Then, select Create. 创建 RunbookCreate Runbook

  5. 此时会创建 Runbook 并打开“编辑 PowerShell Runbook”页。The runbook is created and the Edit PowerShell Runbook page opens. 编辑 RunbookEdit the Runbook

  6. 将以下 PowerShell 示例复制到“编辑”页中。Copy the following PowerShell example into the Edit page. 确保 VaultName 指定你为密钥保管库选择的名称。Ensure that the VaultName specifies the name you've chosen for your Key Vault.

    Param(
      [Parameter(Mandatory=$True)]
      [String] $destEmailAddress,
      [Parameter(Mandatory=$True)]
      [String] $fromEmailAddress,
      [Parameter(Mandatory=$True)]
      [String] $subject,
      [Parameter(Mandatory=$True)]
      [String] $content
    )
    
    $Conn = Get-AutomationConnection -Name AzureRunAsConnection
    Connect-AzAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint | Out-Null
    $VaultName = "<Enter your vault name>"
    $SENDGRID_API_KEY = (Get-AzKeyVaultSecret -VaultName $VaultName -Name "SendGridAPIKey").SecretValueText
    $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
    $headers.Add("Authorization", "Bearer " + $SENDGRID_API_KEY)
    $headers.Add("Content-Type", "application/json")
    
    $body = @{
    personalizations = @(
        @{
            to = @(
                    @{
                        email = $destEmailAddress
                    }
            )
        }
    )
    from = @{
        email = $fromEmailAddress
    }
    subject = $subject
    content = @(
        @{
            type = "text/plain"
            value = $content
        }
    )
    }
    
    $bodyJson = $body | ConvertTo-Json -Depth 4
    
    $response = Invoke-RestMethod -Uri https://api.sendgrid.com/v3/mail/send -Method Post -Headers $headers -Body $bodyJson
    
  7. 选择“发布”以保存并发布 Runbook。Select Publish to save and publish the runbook.

若要验证 runbook 是否成功执行,可以按测试 runbook启动 runbook 下的步骤操作。To verify that the runbook executes successfully, you can follow the steps under Test a runbook or Start a runbook.

如果一开始看不到测试电子邮件,请检查 Junk 和 Spam 文件夹。If you don't initially see your test email, check your Junk and Spam folders.

在电子邮件操作后清理资源Clean up resources after the email operation

  1. 如果不再需要该 runbook,请在 runbook 列表中选中它,然后单击“删除”。When the runbook is no longer needed, select it in the runbook list and click Delete.

  2. 使用 Remove-AzKeyVault cmdlet 删除密钥保管库。Delete the Key Vault by using the Remove-AzKeyVault cmdlet.

$VaultName = "<your KeyVault name>"
$ResourceGroupName = "<your ResourceGroup name>"
Remove-AzKeyVault -VaultName $VaultName -ResourceGroupName $ResourceGroupName

后续步骤Next steps