无法使用PowerShell通过SMTP服务器发送电子邮件

时间:2017-01-02 16:40:36

标签: email powershell smtp

我正在尝试使用PowerShell通过SMTP发送电子邮件。

我已将这些变量存储在 config.ps1 文件中

$smtpServer = "10.0.52.10"
$emailFrom = "prudhvi.g@xiomi.com"
$emailTo = "prudhvi@gmail.com"
$emailsubject = "Health Check"
$emailbody = "Hi"

这是我发送电子邮件的脚本:

##################################################
#Send email with results
##################################################
. .\config.ps1

foreach ($line in $bodystring) 
    {
    $emailbody = $emailbody + $line + "`r`n"
    }


Send-MailMessage -To "$emailTo" -From "$emailFrom" -smtpServer "$smtpserver" -subject "$emailsubject" -body "$emailbody"

我收到此错误:

Send-MailMessage : Unable to connect to the remote server
At C:\Users\administrator.SDC\Desktop\email.ps1:12 char:1
+ Send-MailMessage -To "$emailTo" -From "$emailFrom" -smtpServer "$smtpserver" -su ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpExcept
   ion
    + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage

我的错是什么?我应该包含其他内容以使其有效吗?

1 个答案:

答案 0 :(得分:3)

使用Gmail,我有更多的运气,如下所示。我正在使用这个,因为我们说话,它工作得很好。

$EmailTo = "UserNameHere@gmail.com"
$EmailFrom = "UserNameHere@gmail.com"
$Subject = "New Posting"
$Body = $text 
$SMTPServer = "smtp.gmail.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("UserNameHere@gmail.com", "PasswordHere");
$SMTPClient.Send($SMTPMessage)

我认为UserName,Password,SSL和Port都必须在那里才能使用Gmail。我错了。您还需要确保将Gmail设置为允许此操作。

编辑:如果您尚未执行此操作,请允许您的Gmail在安全设置中使用安全性较低的应用,否则可能会被阻止。您可以在此处查看更多内容并进行配置。 https://myaccount.google.com/intro/security