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
相关产品推荐
相关产品推荐

