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 = "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 )
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.