我正在尝试从发送电子邮件的Windows Server 2012 R2(PowerShell版本4)运行PowerShell脚本。我可以telnet到smtp.gmail.com端口587。 但是,电子邮件没有发送出去。
以下是代码段和例外情况。
$RPT_PWD='userpass'
$Attachment = $args[2]
$EmailTo = $args[1]
$Subject = $args[0]
$EmailFrom = "usertest@gmail.com"
$SmtpServer = "smtp.gmail.com"
$SmtpPort = "587"
$SMTPClient = New-Object System.Net.Mail.SmtpClient($SmtpServer, $SmtpPort)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object
System.Net.NetworkCredential($EmailFrom,$RPT_PWD); # credentials to be used
$objMessage = New-Object System.Net.Mail.MailMessage
$Body = "Email Body"
$objMessage = New-Object System.Net.Mail.MailMessage –ArgumentList
$EmailFrom, $EmailTo, $Subject, $Body
$objMessage.Attachments.Add($Attachment)
$SMTPClient.Send($objMessage)
Exception calling "Send" with "1" argument(s): "Failure sending mail."
At E:\Scripts\DailySystemProcessCheck\EmailTest\mailx_ssl.ps1:133 char:2
+ $SMTPClient.Send($objMessage)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
另外,我也尝试使用send-mailmessage
,但它也没有用。
$Credentials = New-Object System.Management.Automation.PSCredential -
ArgumentList $EmailFrom, $($RPT_PWD | ConvertTo-SecureString -AsPlainText -Force)
send-mailmessage -from $EmailFrom -to $EmailTo -subject $Subject -body $Body
-Attachment $Attachment -smtpServer smtp.gmail.com -Credential $Credentials
-UseSsl -Port 587
~~~~
send-mailmessage : The client and server cannot communicate, because they do
not possess a common algorithm
At E:\Scripts\DailySystemProcessCheck\EmailTest\mailx_ssl.ps1:131 char:2
+ send-mailmessage -from $EmailFrom -to $EmailTo -subject $Subject -body
$Body -A ...
+
+ CategoryInfo : InvalidOperation:
(System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpExcept
ion
+ FullyQualifiedErrorId :
SmtpException,Microsoft.PowerShell.Commands.SendMailMessage
我尝试使用“Powershell --Version 2.0”运行脚本,现在我看不到SMTP Exception,而是看到另一个。
Send : Exception calling "Send" with "1" argument(s): "A from address must
be specified."
At E:\Scripts\DailySystemProcessCheck\EmailTest\mailx_ssl.ps1:124 char:18
+ $SMTPClient.Send <<<< ($objMessage)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
任何人都可以提出建议吗? 提前致谢