通过 Gmail SMTP 从 Powershell 发送邮件

Rit*_*rya 3 powershell gmail smtp

我正在尝试创建一个 powershell 脚本,该脚本应使用 Gmail SMTP 服务发送邮件。这是我的 powershell 版本 -

Get-Host | Select-Object Version

Version
-------
5.1.14393.3866
Run Code Online (Sandbox Code Playgroud)

在研究并尝试不同的代码后,我无法通过 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 )
Run Code Online (Sandbox Code Playgroud)

每当我运行此代码时,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
Run Code Online (Sandbox Code Playgroud)

我已在 Gmail 设置中启用“使用安全性较低的应用程序进行身份验证”。

需要一些帮助来解决这个问题。另外,如果有人可以建议如何添加附件,那将会非常有帮助。

更新和修复:

据我从Google支持了解到,目前对于个人Gmail smtp,我们需要设置2因素身份验证。但是当我们使用gsuite帐户时,一切都很顺利。

HO *_*Pin 6

2022 年 5 月 30 日之后,Google 不再支持安全性较低的应用程序。要解决 Powershell gmail 错误消息 “5.7.0 需要身份验证”,您需要使用以下步骤为您的 Google 帐户打开应用程序密码。

  1. 登录您的 Gmail,http://gmail.google.com
  2. 登录后,请访问https://myaccount.google.com/signinoptions/two-step-verification,确保您在 gamil 帐户上启用了“两步验证”。
  3. 然后通过https://security.google.com/settings/security/apppasswords创建您的应用程序密码
  4. 下面的屏幕将加载,单击“选择应用程序”下拉控件并选择“其他”,然后为其指定一个值,例如 PowershellApp ,然后单击“生成”按钮 在此输入图像描述
  5. 您将得到一个16位的App密码,现在记下来。
  6. 最后,去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
Run Code Online (Sandbox Code Playgroud)