我正在使用 Powershell 和 Exchange Web 服务 (v1.2) 通过 Office 365 发送电子邮件。只要我使用我的凭据,脚本就可以毫无问题地发送。但是,出于跟踪目的,对于脚本错误,我需要从共享邮箱而不是通过我的帐户发送电子邮件。我得到的错误是:
Exception calling "AutodiscoverUrl" with "2" argument(s): "The Autodiscover service couldn't be located."
At F:\Scripting\1-Dev\Modules\Include.ps1:387 char:31
+ $service.AutodiscoverUrl <<<< ($Credential.UserName, {$true})
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
我确定问题出在身份验证上。如何从 o365 中的共享邮箱进行身份验证和发送?
编辑:这是我用来发送电子邮件的代码:
Function Send-O365Email {
[CmdletBinding()]
param(
[Parameter(Position=1, Mandatory=$true)]
[String[]] $To,
[Parameter(Position=2, Mandatory=$true)]
[String] $Subject,
[Parameter(Position=3, Mandatory=$true)]
[String] $Body,
[Parameter(Position=4, Mandatory=$true)]
[System.Management.Automation.PSCredential] $Credential,
[Parameter(Mandatory=$false)]
[String]$PathToAttachment
)
begin {
#Load the EWS Managed API Assembly
Add-Type -Path 'C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll'
}
process {
#Create the EWS service object
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList Exchange2010_SP1
#Set the credentials for Exchange Online
$service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials -ArgumentList `
$Credential.UserName, $Credential.GetNetworkCredential().Password
#Determine the EWS endpoint using autodiscover
$service.AutodiscoverUrl($Credential.UserName, {$true})
#Create the email message and set the Subject and Body
$message = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service
$message.Subject = $Subject
$message.Body = $Body
$message.Body.BodyType = 'HTML'
if (Test-Path $Attachment) {
$message.Attachments.AddFileAttachment("$Attachment");
}
#Add each specified recipient
$To | ForEach-Object {
$null = $message.ToRecipients.Add($_)
}
#Send the message and save a copy in the users Sent Items folder
try {
$message.SendAndSaveCopy()
}
catch [exception] {
Add-Content -Path $LOGFILE -Value "$_"
}
} # End Process
}