You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure通信服务PowerShell脚本报错:无法找到EmailClient类型

解决Azure通信服务PowerShell脚本找不到EmailClient类型的问题

问题根源

你用的Microsoft.Azure.Communication.Administration.EmailClient类型根本不存在于Az.Communication模块中——这个模块仅用于管理Azure通信服务资源,不提供直接发送邮件的能力。要发送邮件,需要使用Azure Communication Email专用的.NET SDK,且正确的类型是Microsoft.Azure.Communication.Email.EmailClient。

解决步骤

1. 安装Azure Communication Email SDK

以管理员身份运行PowerShell,执行以下命令安装对应NuGet包:

Install-Package Microsoft.Azure.Communication.Email -Scope CurrentUser

如果提示找不到包源,先添加NuGet源:

Register-PackageSource -Name NuGet -Location https://api.nuget.org/v3/index.json -ProviderName NuGet

2. 修正代码错误

你的代码存在两处关键问题:

  • 类型名称错误:移除Administration后缀,改用正确的Email.EmailClient
  • 语法错误:$SenderEmailAddress变量缺失开头引号

以下是修正后的完整代码:

Connect-AzAccount
# Az.Communication用于资源管理,发邮件无需依赖,可保留或移除
# Import-Module -Name Az.Communication

# 修正引号缺失问题
$SenderEmailAddress = "xx.azurecomm.net"
$ReceiverEmailAddress = "xx@xx.com"
$EmailConnectionString = "endpoint=xxx"

function Send-Email {
    param (
        [string]$Subject,
        [string]$Body
    )

    $Message = @{
        "content" = @{
            "subject" = $Subject
            "plainText" = $Body
        }
        "recipients" = @{
            "to" = @(
                @{
                    "address" = $ReceiverEmailAddress
                }
            )
        }
        "senderAddress" = $SenderEmailAddress
    }

    # 修正类型名称,使用正确的EmailClient
    try {
        $EmailClient = [Microsoft.Azure.Communication.Email.EmailClient]::FromConnectionString($EmailConnectionString)
        $EmailClient.BeginSend($Message)
        Write-Host "邮件发送请求已提交"
    }
    catch {
        Write-Host "发送失败: $_"
    }
}

$SevenDaysAgo = (Get-Date).AddDays(-7)
$UnusedResources = Get-AzResource | Where-Object { $_.Properties.LastModifiedTime -lt $SevenDaysAgo }

if ($UnusedResources.Count -gt 0) {
    $Subject = "过去7天未使用的Azure资源"
    $Body = "以下Azure资源过去7天未被使用:`n`n"
    foreach ($Resource in $UnusedResources) {
        $Body += "资源名称: $($Resource.Name)`n资源类型: $($Resource.Type)`n最后修改时间: $($Resource.Properties.LastModifiedTime)`n`n"
    }
    Send-Email -Subject $Subject -Body $Body
}
else {
    Write-Output "过去7天未发现未使用的资源。"
}

3. 手动加载程序集(可选)

如果运行仍提示找不到类型,手动加载SDK程序集:

Add-Type -Path "$env:USERPROFILE\.nuget\packages\microsoft.azure.communication email\*\lib\netstandard2.0\Microsoft.Azure.Communication.Email.dll"

将*替换为你安装的具体版本号,比如1.0.0。


内容的提问来源于stack exchange,提问作者user22439645

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 09:33:25