Sending Custom HTML Emails via PowerShell

Hi Everyone,

I hope COVID restrictions are starting to ease for you all. Still, don’t want to let your guard down too much, ey! Better safe than sorry.

In this post, I’m showing a simple way to send HTML emails from PowerShell. This includes sending emails that contain local images instead of hosting them on a separate website. I might have done this in the past, but I want to just throw this out there again. Lets hop in!

First of all, HTML shows different on EVERY SINGLE DEVICE. Outlook is particularly bad, completely ignoring the head that might contain styling and CSS. So the only way around this is to put the styling on every single element in the HTML body.

Here is the HTML I used, we will discuss what is happening below:

<!DOCTYPE html>
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:o="urn:schemas-microsoft-com:office:office">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <meta name="x-apple-disable-message-reformatting">
        <title></title>
        <!--[if mso]>
          <noscript>
             <xml>
                <o:OfficeDocumentSettings>
                   <o:PixelsPerInch>96</o:PixelsPerInch>
                </o:OfficeDocumentSettings>
             </xml>
          </noscript>
          <![endif]-->
        <style>
            table,
            td,
            div,
            h1,
            p {
                font-family: Arial, sans-serif;
            }
        </style>
    </head>
<body style="margin:0;padding:0;">
        <table role="presentation" style="width:100%;border-collapse:collapse;border:0;border-spacing:0">
            <tr>
                <td align="center" style="padding:0;">
                    <table role="presentation"
                        style="width:800px;border-collapse:collapse;border-spacing:0;text-align:left;">
                        <!--Logo-->
                        <tr>
                            <td align="center" style="padding:40px 0 10px 0">
                                <img src="cid:logo.png" alt="" width="350" style="height:auto;display:block;" />
                            </td>
                        </tr>
                        <tr>
                            <td style="padding:10px 10px 10px 10px;">
                                <table role="presentation"
                                    style="width:100%;border-collapse:collapse;border:0;border-spacing:0;">
                                    <!--First chunk-->
                                    <tr>
                                        <td style="padding:0 0 20px 0">
                                            <h1
                                                style="font-size:38px;margin:0 0 20px 0;font-family:Arial,sans-serif;text-align:center;">
                                                Information Technology
                                            </h1>
                                            <p
                                                style="margin:0 0 12px 0;font-size:16px;line-height:24px;font-family:Arial,sans-serif;">
                                                Dear $firstname,
                                            </p>
                                            <h2 style="font-size:22px;margin:0 0 10px 0;font-family:Arial,sans-serif">
                                                Welcome!
                                            </h2>
                                            <p
                                                style="margin:0 0 12px 0;font-size:16px;line-height:24px;font-family:Arial,sans-serif;">
                                                Generic text can go here
                                            </p>
                                            <h2 style="font-size:22px;margin:0 0 10px 0;font-family:Arial,sans-serif">
                                                Your Login Information
                                            </h2>
                                            <p>
                                                style="margin:0 0 12px 0;font-size:16px;line-height:24px;font-family:Arial,sans-serif;">
                                                More generic text
                                           </p>
                                            <p>
                                                style="margin:0;font-size:16px;line-height:24px;font-family:Arial,sans-serif;">
                                            </p>
                                        </td>
                                    </tr>
								</table
							</td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
        </td>
        </tr>
        <!--Footer-->
        <tr>
            <td style="padding:30px;background:#272a36;">
                <table role="presentation"
                    style="width:100%;border-collapse:collapse;border:0;border-spacing:0;font-size:9px;font-family:Arial,sans-serif;">
                    <tr>
                        <td style="padding:0;width:50%;" align="center">
                            <p style="margin:0;font-size:18px;line-height:16px;font-family:Arial,sans-serif;color:#ffffff;">
                                For an additional support, or if you have any questions, please
                                send an email to <a href="mailto:help@example.com"
                                    style="color:#d6d6d6;text-decoration:underline;">help@example.com</a>
                            </p>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        </table>
        </td>
        </tr>
        </table>
    </body>
</html>
  • Setting the Office product details and pixel density information
  • The logo.png is loaded using the cid: prefix which looks at the loaded images, you can see this below
  • The rest is just generic HTML with inline styling

Next we need to start creating the PowerShell email object.

#Define a valid SMTP server to send your emails through
$smtpServer = 'SERVER HERE' #e.g smtp.local.com
#Define a new SMTP object using the server defined above
$smtpObject = New-Object Net.Mail.SmtpClient($smtpServer)

#Create a new mail message object 
$msg = New-Object Net.Mail.MailMessage
$msg.From = 'DoNotReply@example.com'
$msg.ReplyTo = 'bccemail@example.com'
$msg.BCC.Add('bccemail@example.com')
$msg.To.Add('recipient@example.com')
$msg.subject = 'Example Email Subject'
$msg.IsBodyHtml = $True

$msg.Body = 'HTML FROM ABOVE - This can be a separate variable or right here'

#Provide a path to the photos for the email
$scriptPath = 'C:\example'

#Create a new mail attachment as an image
$logo = New-Object System.Net.Mail.Attachment -ArgumentList "$scriptPath\logo.png"
$logo.ContentDisposition.Inline = $True
$logo.ContentDisposition.DispositionType = "Inline"
$logo.ContentType.MediaType = "image/png"
$logo.ContentId = 'logo.png'

#Add the image attachment to the email, this allows the HTML to use the cid: prefix
$msg.Attachments.Add($logo)

#Try to send the email
try{
    $smptObject.Send($msg)
}catch{
    Write-Host 'Failed to send the email: ' -ForegroundColor Red -NoNewLine
    Write-Host $Error[0] -ForegroundColor Red
}

#Dispose of the image attachments and the email object to avoid memory leaks
#logo.Dispose()
$msg.Dispose()

Hopefully this shows just how easy it is to create and send HTML emails using PowerShell, including images send directly from the script instead of hosting them and suppling a web page URL.

If you have any questions etc, feel free to comment and I’ll help however I can.

Enjoy! ?

Swaks Email Scripting

Hi, in this blog post I will show you how I configured Swaks for sending emails using SMTP using my custom SMTP server.

First I ran the following command to install swaks:

sudo apt-get install swaks

With swaks installed, I could start building a test command just to
see if this would actually work. I started with the below command:

swaks --to destination@email.com --from source@email.com --auth --auth-user=source@email.com --auth-password=passwordforsource@email.comaccount --server smtp.example.com -tls

This gave me an error along the lines of “Could not authenticate – connection refused” after talking to the people hosting my SMTP server, I found out that I needed to make sure that I was using port 587 and not the default port of 465.

So I made sure that my command explicitly used that port by adding it to the server parameter and managed to get an email to successfully send. You can see the code I used below:

swaks --to destination@email.com --from source@email.com --auth --auth-user=source@email.com --auth-password=passwordforsource@email.comaccount --server smtp.example.com:587 -tls

Extra

I wanted to use this in a script so that I could launch the script and an email would get sent. I also wanted to change what would get sent in the actual email since currently, it was just using the default values.

After 5 or so minutes of cobbling a script together, I came up with what you can see below:

#!/bin/bash

hostname=$(hostname)
uptime=$(uptime)

swaks --to destination@email.com \
--from=source@email.com \
--auth \
--auth-user=source@email.com \
--auth-password=password-for-source-email \
--server smtp.example.com:587 \
--body "$hostname - uptime is $uptime" \
--header "Subject: $hostname is still up" \
-tls \

Now I can send this email whenever I want, I even created a CRON job to send the email every hour. Enjoy!