How to send an email with an attachment using PowerShell?

How to send an email with an attachment using PowerShell?

Windows PowerShell is mostly known as a command-line shell used to complete administrative tasks in Windows and the apps that run on it. It is also a scripting language that allows you to create cmdlets – lightweight commands to perform specific functions.

Send-MailMessage is an example of a cmdlet to send emails from PowerShell.

There are other methods to handle this as well.:

The simplest script to send an email with PowerShell with Attachment.

Here is a one-line script based on the Send-MailMessage cmdlet you can use to send an email from PowerShell using SMTP protocol with an attachment.

$User = "sks@leapwork.com"
$File = "C:\Users\SauravKumarSinha\Desktop\Password.txt"
$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $File | ConvertTo-SecureString -AsPlainText -Force)
$EmailTo = "sks@leapwork.com"
$EmailFrom = "sks@leapwork.com"
$Subject = "Email Subject"
$Body = "Email body text"
$SMTPServer = “outlook.office365.com"
$filenameAndPath = "C:\Users\SauravKumarSinha\Desktop\Saurav.png"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SMTPServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($cred.UserName, $cred.Password);
$SMTPClient.Send($SMTPMessage)

File: You need to specify the password file Path. Typically Notepad Password.txt File format could be in the below format.


Description of the above-used parameter in the PowerShell script:

Parameter Description
-To The email address of a recipient or recipients
-Bcc The email address of a BCC recipient or recipients
-Cc The email address of a CC recipient or recipients
-From Sender’s email address
-Subject Email subject
-Body Email body text
-BodyAsHtml Defines that email body text contains HTML
-Attachments Filenames to be attached and the path to them
-Credential Authentication to send the email from the account
-SmtpServer Name of the SMTP server
-Port Port of the SMTP server

Integration and Execution of this script in Windows PowerShell ISE :

Leapwork Integration with this PowerShell script:

Success Email will be triggered as shown below:


For clarification, please contact our Priority Support.