Search code examples
powershellemailgmailazure-devopsrelease-management

Sending email via GMAIL using Powershell in VSTS


I want to send an email at the end of a VSTS release with some additional data. I am using a powershell release task and am using the Gmail SMTP server. The powershell script is as follows:

$b = Invoke-WebRequest "http://mywebsite" -usebasicparsing
$message = New-Object System.Net.Mail.MailMessage
$message.subject =  "Swagger"
$message.body = $b
$message.to.add("[email protected]")
$message.from = "[email protected]"
$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)

Since I am using 2 factor authentication, I am using an app password in the code above. This works fine when I run it from my local machine. However, as part of the release process, it gives me the following error:

"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required"

Can anyone point me in the right direction? Thanks!


Solution

  • Could you please try this:

    $SMTPServer = "smtp.gmail.com"
    $SMTPPort = "587"
    $Username = "[email protected]"
    $Password = "password"
    $to = "[email protected]"
    #$cc = "[email protected]"
    $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"