发送电子邮件时出现PowerShell错误

时间:2016-06-01 08:58:58

标签: powershell smtpclient

我有以下用于发送电子邮件的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

这段代码有什么问题?

2 个答案:

答案 0 :(得分:1)

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

此代码适用于我,smtp.live.com587 SSL端口$SmtpServer = 'smtp.live.com' $SmtpUser = 'your_username@outlook.com' $smtpPassword = 'your_password' $MailtTo = '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 "$MailtTo" -from "$MailFrom" -Subject $MailSubject -SmtpServer $SmtpServer -Credential $Credentials -UseSsl -Port 587 没有任何问题

{{1}}

答案 1 :(得分:0)

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