Sending email with Gmail account using PowerShell script

Send email with your Gmail account login with PowerShell script

Sending email after and even before a long running PowerShell script is a logical thing to do to notify users which are responsible for taking actions for the specific operation. 

PowerShell starting from version 3.0 has build in cmdlet Send-MailMessage for sending emails.

Param(
[Parameter(Mandatory=$true)]
[string]$emailTo,
[Parameter(Mandatory=$true)]
[string]$subject,
[Parameter(Mandatory=$true)]
[string]$body
)

$smtpUsername = "username@gmail.com"
$smtpPassword = "password"
$credentials = new-object Management.Automation.PSCredential $smtpUsername, ($smtpPassword | ConvertTo-SecureString -AsPlainText -Force)
Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -UseSsl -Credential $credentials -From $smtpUsername -To $emailTo -Subject $subject -Body $body
    
Note

More documentation about Send-MailMessage can be found in online Microsoft PowerShell documentation https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage?view=powershell-3.0

In case for some reason this does not work for you can always rely on .NET to do the email sending for you from PowerShell

Param(
[Parameter(Mandatory=$true)]
[string]$emailFrom,
[Parameter(Mandatory=$true)]
[string]$emailTo,
[Parameter(Mandatory=$true)]
[string]$subject,
[Parameter(Mandatory=$true)]
[string]$body
)


$smtpServer = "smtp.gmail.com" 
$smtpUsername = "username@gmail.com"
$smtpPassword = "password"
$smtpClient = New-Object Net.Mail.smtpClient($smtpServer, 587) 
$smtpClient.EnableSsl = $true 
$smtpClient.Credentials = New-Object System.Net.NetworkCredential($smtpUsername, $smtpPassword); 
$smtpClient.Send($emailFrom, $emailTo, $subject, $body)
    

 

References

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan Stojanovic is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform includion ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

.NET

read more

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

Comments for this article