使用VSTS中的Powershell通过GMAIL发送电子邮件

时间:2017-11-13 11:54:06

标签: powershell email gmail azure-devops release-management

我想在VSTS版本的末尾发送一封电子邮件,其中包含一些其他数据。我正在使用powershell发布任务并使用Gmail SMTP服务器。 powershell脚本如下:

$b = Invoke-WebRequest "http://mywebsite" -usebasicparsing
$message = New-Object System.Net.Mail.MailMessage
$message.subject =  "Swagger"
$message.body = $b
$message.to.add("me@hotmail.com")
$message.from = "source@gmail.com"
$smtp = New-Object System.Net.Mail.SmtpClient("smtp.gmail.com", "587");
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, "apppassword");
$smtp.send($message)

由于我使用的是2因素身份验证,因此我在上面的代码中使用了应用密码。当我从本地计算机运行它时,这工作正常。但是,作为发布过程的一部分,它会给我以下错误:

  

" SMTP服务器需要安全连接,否则客户端不需要   认证。服务器响应为:5.5.1需要验证"

有人能指出我正确的方向吗?谢谢!

1 个答案:

答案 0 :(得分:0)

请你试试这个:

$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$Username = "username@gmail.com"
$Password = "password"
$to = "username_to_send@gmail.com"
#$cc = "username@gmail.com"
$subject = "Email Subject"
$body = "Insert body text here"
#$attachment = "C:\attachedFile.txt"
$message = New-Object System.Net.Mail.MailMessage
$message.subject = $subject
$message.body = $body
$message.to.add($to)
#$message.cc.add($cc)
$message.from = $username
#$message.attachments.add($attachment)
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)
write-host "Mail Sent successfully using GMAIL"