【问题标题】:unable to send mail from powershell无法从 powershell 发送邮件
【发布时间】:2020-08-05 11:45:22
【问题描述】:

无法使用 gmail 通过 powershell 发送邮件。该代码检查网站是否可以访问并发送电子邮件。

允许访问安全性较低的应用 - 已开启,两步验证开启并生成应用密码。

错误:Send-MailMessage:无法从传输连接读取数据:net_io_connectionclosed.. 请参阅下面的代码:


$recipient = "recipeint email"
$smtpUser = "sender email"
$mysubject = "Daily Checks"
$mailbodyonline = “Good day, The Website is available” 
$mailbodyoffline = “Good day, The Website is not available”
$mailserver = "smtp.gmail.com"


$smtpPassword = "C:\mySriptFile\siteemailpass.txt"

$mypassword = ConvertTo-SecureString $smtpPassword -AsPlainText -Force

$Creds = New-Object -TypeName System.Management.Automation.PSCredential $smtpUser, $mypassword



$progressPreference = 'silentlyContinue'
$HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')

$HTTP_Request.Timeout=10000;


$progressPreference = 'Continue'


$HTTP_Response = $HTTP_Request.GetResponse()

$HTTP_Status = [int]$HTTP_Response.StatusCode


If ($HTTP_Status -eq 200) {


Send-MailMessage -To $recipient -From $smtpUser  -Subject $mysubject -Body $mailbodyonline -Credential $Creds -SmtpServer $mailserver -UseSsl -Port 465 -encoding UTF8
}

Else
{
    Send-MailMessage -To $recipient -From $smtpUser  -Subject $mysubject -Body $mailbodyoffline -Credential $Creds -SmtpServer $mailserver -UseSsl -Port 465 -encoding UTF8
}


If ($HTTP_Response -eq $null) { } 


Else { $HTTP_Response.Close() }


当我将端口从 465 更改为 587 时,我收到以下错误; Send-MailMessage :SMTP 服务器需要安全连接或客户端未通过身份验证。服务器响应为:需要 5.7.0 身份验证。

我们将不胜感激任何帮助和建议, 提前致谢。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    为了通过smtp.gmail.com发送邮件,你需要先做一些gmail配置。

    1. 在 google 安全控制面板中启用“不太安全的应用程序”(好像您已经这样做了)。
    2. 确保禁用两因素身份验证。 (我认为这就是您的代码出错的原因)
    3. 确保“验证码”已禁用。

    顺便说一句,您永远不应该在代码中使用卷曲的“智能引号”

    【讨论】:

      【解决方案2】:

      感谢您的回复,我设法解决了问题。代码无法从文本文件中获取密码,我不得不重新创建文本文件。换了。

      $smtpPassword = "C:\mySriptFile\siteemailpass.txt"

      $mypassword = ConvertTo-SecureString $smtpPassword -AsPlainText -Force

      $Creds = New-Object -TypeName System.Management.Automation.PSCredential $smtpUser, $mypassword with $smtpPassword = Get-Content "C:\mySriptFile\siteemailpass.txt" | ConvertTo-SecureString

      $Creds = New-Object -TypeName System.Management.Automation.PSCredential $smtpUser, $smtpPassword

      它现在可以工作了。感谢您的快速回复

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-03
        • 2016-05-30
        • 2014-04-06
        • 2021-04-29
        • 1970-01-01
        • 2015-03-13
        • 2018-02-01
        • 2013-07-15
        相关资源
        最近更新 更多