PowerShell Send Email using SMTP
Today in this example, We will implement PowerShell Send Email using SMTP functionality. To make this even simpler I have used my own Gmail( modified below) for sending an email and testing purposes which worked very well after some initial travail.
We will Send-MailMessage cmdlet to send an email message with attachments using the SMTP server and client.
Today in this article, we will cover below aspects,
Send-MailMessage cmdlet to send email
The Send-MailMessage
cmdlet sends an email message using PowerShell conveniently.
You must specify a Simple Mail Transfer Protocol (SMTP) server details using Net.Mail.SmtpClient.Below I have used Gmail SMTP server details.
Below is the code added to send email in PowerShell
$message = new-object Net.Mail.MailMessage;
$message.From = "go.digital.development@gmail.com";
$message.To.Add($email);
$message.Subject = "Sending email from PowerShell";
$message.Body = "Hi There";
$smtp = new-object Net.Mail.SmtpClient("smtp.gmail.com", "587");
$smtp.EnableSSL = $true;
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message);
Powershell- Send an email with attachment
If you want to send an email with the attachments, Please specify the attachments as below,
$attachment = New-Object Net.Mail.Attachment($attachmentpath);
$message.Attachments.Add($attachment);
To make use of GMAIL to send emails to other domains, you need to use some settings to make it work.
I also got an email from Gmail saying “Critical security alert for your linked Google Account.”
- I had to enable “Allow less secure apps: ON” to make send email API work properly.
Once configured successfully you shall see an email in your mailbox.
Note: As per Microsoft The Send-MailMessage
cmdlet is obsolete. This cmdlet does not guarantee secure connections to SMTP servers. For more details see here
References :
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.
Google No longer supports the “allow less secure apps” in Gmail. Do you have a work around or know of another SMTP server that will allow this?
Hi Trent- Thanks for your query. Using your Gmail account password is recommended and it was used for just testing purpose.
You can create an Application Password using the feature “apppasswords” – https://myaccount.google.com/apppasswords and then use the same as password. Here you need to first Turn on 2 step verification for your gmail account.
Hope this helps!