Sending an email with attachments using Outlook and PowerShell

A few days ago, I had to find a way to automatically send an email with attachments, at a predetermined time, using Outlook and PowerShell. I decided to use a Windows Scheduled Task, that would wake up at that time and invoke a PowerShell script.

The script below is the result of a collection of snippets and bits of code I found in various places around the Internet that allowed me to solve this problem.

For this example, I only want to send the files which have a specific extension (.html) and that exist in a specific folder (passed as parameter to the PowerShell script). Of course, you are free to remove this extension filtering for your own purposes.

Also, note that Outlook must have a configured email account for the sending process to succeed.

# Check to see we have all the arguments
if($args.Count -lt 1)
Write-Host "Use: SendMail.ps1 <Path>"
Write-Host " <Path>: Full path for the folder which contains the files"


#Get an Outlook application object

$o = New-Object -com Outlook.Application

$mail = $o.CreateItem(0)

#2 = High importance message
$mail.importance = 2

$mail.subject = "This is the subject of the mail"
$mail.body = "This is the body of the email. It has been automatically generated by a script."

#separate multiple recipients with a ";"

# Iterate over all files and only add the ones that have an .html extension
$files = Get-ChildItem $FullPath

for ($i=0; $i -lt $files.Count; $i++) {

$outfileName = $files[$i].FullName
$outfileNameExtension = $files[$i].Extension

# if the extension is the one we want, add to attachments
if($outfileNameExtension -eq ".html")


# give time to send the email
Start-Sleep 20

# quit Outlook

#end the script

You can invoke the script presented above, by using a simple command window and giving the following command:

PowerShell Command

I hope this helps!