Monday, 20 February 2017

PowerShell Send Email with Gmail, PS V. 2.0 or Higher

Hi All, here a free script to sending email with gmail and powershell v 2.0 or higher:
If you get error on sending like:

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.5.1 Authentication Required. Learn more at"...

You MUST enable less secure App access on your gmail's account
https://myaccount.google.com/security

<#
LWEBCODE Mail Sender
On your gmail account enable less secure App access

https://myaccount.google.com/security

In code above replace GMAILUSER with your gmail's user:
lwebcode123@gmail.com=>lwebcode123
#>
function sendmail
{
    $smtpClient = new-object system.net.mail.smtpClient
    $smtpClient.Host = "smtp.gmail.com"
    $smtpClient.Port = 587
    $smtpClient.EnableSsl = $true
    $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("GMAILUSER", "password");
      
    $emailfrom = "lwebcode123@gmail.com"
    $emailto = "lwebcode123@gmail.com"
    $subject = "test"
    $body = "this is body"

    $emailMessage = New-Object System.Net.Mail.MailMessage
    $emailMessage.From = $EmailFrom
    $emailMessage.To.Add($EmailTo)
    $emailMessage.Subject = $Subject
    $emailMessage.Body = $Body
    $emailMessage.Attachments.Add("C:\lwebcode\attachement.txt")
    $SMTPClient.Send($emailMessage)
}
sendmail

No comments:

Post a Comment