During a recent assignment I got an automation requirement to send formatted emails daily to a set of users.
The email content involved the HTML formatting with a lot of images as a part of the layout. I have appointed PowerShell as the automation technology to get this done.
I felt it would be worth writing a small article to explain the code (which is interesting) to embed images within the outgoing email content.
Now to start with a demo, say we have to send an email with Health of Weekly Sales Card for an online shopping store every week on Monday.
This email would look like the one in the following screenshot,
In Steps 1, 2, 4 we are defining HTML that will be sent as Email Content.
Here it is very important to notice the “SRC” Tag where we are specifying image path not as an actual path but as a Content Identifier that is mapped to the path of the attachment added to the email.
And this is the trick that you have to remember to get the images embedded into the HTML body of the email.
Now, once we are done with defining body content for Email Body, we can start configuring SMTP Client and adding the attachments to the email.
In Step 5 we will initialize “SMTP Server”, “Mail Message”, and “SMTP Client” Objects
Step 6 configure “From” & “To” Email IDs for the intended recipients. Also, specify the “Subject” & “Body” for the email
In Step 7 & 8 we will add attachments to the email and provide each attachment a Content Identifier (remember we used this identifier in “SRC” Tag while defining HTML content for the body).
Attachments can be added to the email by using object of “Attachment” Class.
While initializing the “Attachment” Object we have to provide an actual path of the attachment as an input parameter
Then we have to make sure that
- “Inline” property should be set to “True”,
- “DispositionType” property should be set to “Inline”,
- “MediaType” property should be set to “<type of content, you are attaching>”,
- “ContentId” property should be set to any unique Content Identifier to represent the attachment uniquely
In Step 9 we will send the email by calling in “Send” method of SMTP Client object. Make sure to dispose of the “Attachments” & “Mail Message” objects.
And finally, we will call the Send-Email Function in Step 10 to run all the code snippets described earlier.
Code Snippet
That is all for this demo.
I hope you find it helpful.