- Sending HTML-formatted email body using Shell PowerShell
- Sending Automated emails with Send-MailMessage, ConvertTo-HTML, and the PowerShellPack’s TaskScheduler module
- PowerShell Automation — How To Send Email With HTML Body Containing Inline Images
- Send HTML Format E-Mails with Send-MailMessage in PowerShell
- How to use Send-MailMessage with HTML body?
- Send-MailMessage in PowerShell with attachments:
- Send-mailmessage in PowerShell to multiple recipients:
Sending HTML-formatted email body using Shell PowerShell
Sending Automated emails with Send-MailMessage, ConvertTo-HTML, and the PowerShellPack’s TaskScheduler module
The PowerShellPack, a vast collection of PowerShell V2 scripts, was launched by me on October 15th. These scripts are not only enjoyable but also practical in nature, as they can be used for various purposes. In this article, we will demonstrate how to schedule automated daily emails containing details about the installed programs on a specific system using a module from the PowerShellPack.
PowerShell V2 makes it easy to transform the result of a PowerShell script into an automated email. This is accomplished through the use of the Send-MailMessage cmdlet, which permits the sending of emails using either the current user’s credentials or those of a different user, along with an SMTP server. Additionally, Send-MailMessage can send emails in HTML format by utilizing the –BodyAsHtml switch. To transform cmdlet output into an HTML chunk, ConvertTo-HTML can be used. If an introduction and signature are required, the new –PreContent and –PostContent parameters of ConvertTo-HTML can be utilized.
This script sends an email message promptly using a concise code block that avoids long lines with excessive parameters. Instead, the parameters are kept in a Hashtable and provided to Send-MailMessage using Splatting.
$messageParameters = @ Subject = "Installed Program report for $env:ComputerName.$env:USERDNSDOMAIN - $((Get-Date).ToShortDateString())" Body = Get-WmiObject Win32_Product | Select-Object Name, Version, Vendor | Sort-Object Name | ConvertTo-Html | Out-String From = "Me@MyCompany.com" To = "Me@MyCompany.com" SmtpServer = "SmtpHost" > Send-MailMessage @messageParameters -BodyAsHtml
Having written that portion of code, it is important to ensure that any issues that arise are recorded in a file. This can be achieved by utilizing one of PowerShell’s special variables, $ErrorActionPreference = «Stop», and incorporating try/catch blocks around all the code.
$ErrorActionPreference = "Stop" try $messageParameters = @ Subject = "Installed Program report for $env:ComputerName.$env:USERDNSDOMAIN - $((Get-Date).ToShortDateString())" Body = Get-WmiObject Win32_Product | Select-Object Name, Version, Vendor | Sort-Object Name | ConvertTo-Html | Out-String From = "Me@MyCompany.com" To = "Me@MyCompany.com" SmtpServer = "SmtpHost" > Send-MailMessage @messageParameters -BodyAsHtml > catch $_ | Out-File $env:TEMP\ProblemsSendingHotfixReport.log.txt -Append -Width 1000 >
Ultimately, I will utilize the TaskScheduler module from PowerShellPack to ensure the email is sent on a daily basis. Accomplishing this requires downloading the PowerShellPack onto the designated machine for task scheduling. Implementing the PowerShell Pack for task scheduling involves a brief pipeline, which in our case will resemble the following:
New-Task | Add-TaskAction -Script # Our Emailer Here > | Add-TaskTrigger -Daily -At "9:00 AM" | Add-TaskTrigger -OnRegistration | Register-ScheduledTask "DailyHotfixReport"
Sending an email with the output of a simple cmdlet at 9 AM every day and upon task registration seems effortless, doesn’t it? This technique can also be used for running more complex tasks, and the trigger types can be adjusted to send emails at desired intervals.
New-Task | Add-TaskAction -Hidden -Script $ErrorActionPreference = "Stop" try $messageParameters = @ Subject = "Installed Program report for $env:ComputerName.$env:USERDNSDOMAIN - $((Get-Date).ToShortDateString())" Body = Get-WmiObject Win32_Product | Select-Object Name, Version, Vendor | Sort-Object Name | ConvertTo-Html | Out-String From = "Me@MyCompany.com" To = "Me@MyCompany.com" SmtpServer = "SmtpHost" > Send-MailMessage @messageParameters -BodyAsHtml > catch $_ | Out-File $env:TEMP\ProblemsSendingHotfixReport.log.txt -Append -Width 1000 > > | Add-TaskTrigger -Daily -At "9:00 AM" | Add-TaskTrigger -OnRegistration | Register-ScheduledTask "DailyHotfixReport"
The creation of a scheduled task that sends a comprehensive report of the installed programs on a computer only required 24 lines of PowerShell script. With PowerShell V2, the process of automating emails is effortless, and utilizing the PowerShellPack makes scheduling regular script runs, including this one, a breeze. Overall, it was a painless experience.
Passing the content of txt file to body of Send-MailMessage in, Passing the content of txt file to body of Send-MailMessage in powershell · $path = «H:\userlist.txt» · $groups = Get-Content $path · $groups1 = $
PowerShell Automation — How To Send Email With HTML Body Containing Inline Images
For a recent task, I was tasked with automating the daily delivery of formatted emails to a group of designated recipients.
To incorporate images into the layout, the email utilized HTML formatting, and PowerShell was selected as the automation technology to execute the task.
Considering the fascinating code involved in incorporating images into email content, I believed it would be valuable to compose a brief article to elucidate the process.
To begin a demonstration, let’s assume that we need to send a weekly email on Mondays for an online shopping store containing the Health of Weekly Sales Card.
The email would resemble the screenshot provided below.
It is crucial to observe the «SRC» tag, which specifies the image path using a Content Identifier that maps to the attachment’s path in the email, rather than an actual path.
To embed images into the HTML body of an email, remember this trick.
After defining the content of the email body, we can proceed to configure the SMTP client and include any necessary attachments.
In the fifth step, we will create instances of the «SMTP Server», «Mail Message», and «SMTP Client» objects.
In Step 6, provide the email addresses for both the sender and recipient. Additionally, input the subject and body content of the email.
During Step 7 and 8 of the process, we will include attachments in the email and assign a Content Identifier to each attachment. It is important to note that the same identifier was used in the «SRC» Tag while defining the HTML content for the body.
It is possible to add attachments to an email through the use of the «Attachment» Class object.
To initialize the «Attachment» Object, the input parameter required is the actual path of the attachment.
Then we have to make sure that
- The value of the «Inline» property needs to be set as «True».
- The value of the «DispositionType» property must be specified as «Inline».
- Set the «MediaType» attribute to the type of content being attached.
- To ensure a unique representation of the attachment, the «ContentId» attribute must be assigned a distinct Content Identifier.
The ninth step involves using the «Send» method from the SMTP Client object to send the email. Remember to properly dispose of both the «Attachments» and «Mail Message» objects.
At the end, we will execute the previously mentioned code snippets by invoking the Send-Email Function in Step 10.
Code Snippet
Send HTML Format E-Mails with Send-MailMessage in PowerShell
Requirement: Send E-mail from PowerShell script with HTML formatted body.
How to use Send-MailMessage with HTML body?
Do you need to send an HTML formatted email from PowerShell? If so, you can use the Send-MailMessge cmdlet with the -BodyAsHtml parameter. I will show you how to use the Send-MailMessage cmdlet to send HTML formatted e-mails. I will also provide some PowerShell examples of using HTML formatting in your e-mails.
Here is an example for sending E-mail as HTML from PowerShell script with the Send-MailMessage cmdlet:
#Get Date $ReportDate = Get-Date -format "MM-dd-yyyy" #Configuration Variables for E-mail $SmtpServer = "smtp.crescent.com" #or IP Address such as "10.125.150.250" $EmailFrom = "Site Delete Script " $EmailTo = "SharePointSupport@Crescent.com.com" $EmailSubject = "Site Delete Script - Daily Report on: "+$ReportDate #HTML Template $EmailBody = @"
Site Delete Script - Daily Report on VarReportDate | |
Number of requests Approved | VarApproved |
Number of requests Rejected | VarRejected |
Instead of directly embedding the HTML into the script, you can also store it in an external file and retrieve the HTML format/template with the Get-Content cmdlet in the script.
Send-MailMessage in PowerShell with attachments:
Just specify the -attachments parameter in Send-Mailmessage cmdlet. Here is an example:
#send-mailmessage in powershell with attachment $attachment = "D:\Reports\SiteDeleteRpt.csv" #send-mailmessage in powershell multiple attachments $attachment = "D:\Reports\SiteDeleteRpt1.csv","D:\Reports\SiteDeleteRpt2.csv" Send-MailMessage -To $EmailTo -From $EmailFrom -Subject $EmailSubject -Body $EmailBody -BodyAsHTML -Attachments $attachment -SmtpServer $SmtpServer
Send-mailmessage in PowerShell to multiple recipients:
$EmailTo = "marcm@crescent.com", "victor " #or use: $recipients = @("Marc M ", "victor ")
$SPGlobalAdmin = New-Object Microsoft.SharePoint.Administration.SPGlobalAdmin $SMTPServer = $SPGlobalAdmin.OutboundSmtpServer