我正在尝试创建一个应该使用 Gmail SMTP 服务发送邮件的 powershell 脚本。这是我的 powershell 版本 -
Get-Host | Select-Object Version
Version
-------
5.1.14393.3866
在研究和尝试不同的代码后,我无法通过 Gmail SMTP 从 Powershell 发送电子邮件。这是我的代码:
$emailSmtpServer = "smtp.gmail.com"
$emailSmtpServerPort = "587"
$emailSmtpUser = "mymail@gmail.com"
$emailSmtpPass = "mymailpass"
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "mymail@gmail.com"
$emailMessage.To.Add("myothermail@mail.com")
$emailMessage.Subject = "Small mail for a friend"
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = @"
<p><strong>Hello me</strong>.</p>
<p>It seems to work</p>
<p>JP</p>
"@
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
$SMTPClient.Send( $emailMessage )
每当我运行此代码 powershell 时都会抛出以下错误:
Exception calling "Send" with "1" argument(s): "The SMTP server requires a secure connection or the client was not
authenticated. The server response was: 5.7.0 Authentication Required. Learn more at"
At C:\Users\ritu\Documents\testing.ps1:38 char:1
+ $SMTPClient.Send( $emailMessage )
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
我已经在我的 Gmail 设置中启用了“使用安全性较低的应用程序进行身份验证”。
需要一些帮助来解决这个问题。另外,如果有人可以建议如何添加附件,那将非常有帮助。
更新和修复:
据我从 Google 支持了解到,目前对于个人 Gmail smtp,我们需要设置 2 因素身份验证。但是当我们使用 gsuite 帐户时,一切正常。
最佳答案
安全性较低的应用 no longer supported by google 2022 年 5 月 30 日之后。要解决 Powershell gmail 错误消息'5.7.0 Authentication Required',您需要为您的 google 帐户打开 App password使用以下步骤。
- 登录您的 Gmail,http://gmail.google.com
- 登录后,转到https://myaccount.google.com/signinoptions/two-step-verification ,以确保您在您的 gamil 帐户上启用“两步验证”。
- 然后通过 https://security.google.com/settings/security/apppasswords 创建您的应用程序密码
- 下面的屏幕将加载,单击“选择应用程序”下拉控件并选择“其他”,然后为其赋值,例如 PowershellApp,然后单击“生成”按钮
- 您将获得一个 16 位的 App 密码,现在记下来。
- 最后,转到 https://accounts.google.com/DisplayUnlockCaptcha启用“对您的 Google 帐户的外部访问”
现在您可以通过 Powershell 发送 gmail,使用如下代码
$userName = 'MyGamial@gmail.com'
$To = 'receipient@email.com'
# The 16 digits gmail Acc app password
$password = 'aaaabbbbccccdddd'
[SecureString]$securepassword = $password | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $securepassword
Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -UseSsl -From $userName -To $To -Subject 'Test subject' -Body 'Test message' -Credential $credential
关于powershell - 通过 Gmail SMTP 从 Powershell 发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66044348/