Search code examples
powershellsmtpgmail

Sending mail from Powershell via Gmail SMTP


I am trying to create a powershell script that should send a mail using Gmail SMTP service. This is my powershell version -

Get-Host | Select-Object Version

Version
-------
5.1.14393.3866

After researching & trying different code, I am unable to send Email from Powershell via Gmail SMTP. Here is my code:

$emailSmtpServer = "smtp.gmail.com"
$emailSmtpServerPort = "587"
$emailSmtpUser = "[email protected]"
$emailSmtpPass = "mymailpass"

$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "[email protected]"
$emailMessage.To.Add("[email protected]")
$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 )

Whenever I am running this code powershell is throwing below error:

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

I have already enable "Authenticate with Less Secured App" in my Gmail settings.

Need some help to fix this. Also if anyone can suggest how to add attachment, that will be very helpful.

UPDATE & FIX:

As I understood from Google Support, currently for personal Gmail smtp, we need to setup 2 factors authentication. But when we use gsuite account, everything went fine.


Solution

  • Both the scripts given above would work, The actual issue is with google trying to block as mentioned in the Update on the first post. If you are using personal gmail account, you would need to create a App Password https://myaccount.google.com/apppasswords even after setting with Two factor authentication. Just replace the new password generated in any of the "password" fields and the mail will be triggered.