发送电子邮件时的 PowerShell 错误

PowerShell error on sending e-mail

我有以下用于发送电子邮件的 Powershell 脚本:

$smtpServer = "smtp.live.com"
$smtpPort = "465"
$credential = [Net.NetworkCredential](Get-Credential)

$smtpClient = New-Object System.Net.Mail.SmtpClient $smtpServer, $smtpPort
$smtpClient.EnableSsl=$true
$smtpClient.UseDefaultCredentials=$false
$smtpClient.Credentials= $credential

$smtpTo = "existing_email@hotmail.com"
$smtpFrom = "email@hotmail.com"
$messageSubject = "Testing Mail" 
$messageBody = "Hi, This is a Test"

$message = New-Object System.Net.Mail.MailMessage $smtpFrom, $smtpTo, $messageSubject, $messageBody

try
{
  $smtpClient.Send($message)
  Write-Output "Message sent."
}
catch
{
  $_.Exception.Message
  Write-Output "Message send failed."
}

但是我收到这个错误:

+ CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,mail.ps1

Exception calling "Send with "1" arguments" Failure Sending mail

这段代码有什么问题?

您尚未定义 $smtpFrom(发送电子邮件的地址)。另外,只是一个建议,你为什么不使用 Send-MailMessage cmdlet,它可以从 PowerShell 2.0

获得

此代码适用于 smtp.live.com,端口 587SSL

没有任何问题
$SmtpServer = 'smtp.live.com'
$SmtpUser = 'your_username@outlook.com'
$smtpPassword = 'your_password'
$MailTo = 'your_to_mail@example.com'
$MailFrom = 'your_username@outlook.com'
$MailSubject = "Test using $SmtpServer" 
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $SmtpUser, $($smtpPassword | ConvertTo-SecureString -AsPlainText -Force) 
Send-MailMessage -To "$MailTo" -from "$MailFrom" -Subject $MailSubject -SmtpServer $SmtpServer -Credential $Credentials -UseSsl -Port 587 

我解决了将端口更改为 25。但是为什么我不能使用 IMAP?