During of a recent assignment I get across an automation requirement to send formatted emails daily to a set of users.
The email content involved the HTML formatting with lot of images as a part of layout. I have appointed PowerShell as automation technology to get this done.
I found worth writing a small article to explain the code (which is interesting) to embed images with in outgoing email content.
Now to start with 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 screen shot:
In Step 1,2,4 we are defining HTML that will be send as Email Content.
Here it is very important to notice the “SRC” Tag where we are specifying image path not as 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
In 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 actual path of the attachment as 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 call in “Send” method of SMTP Client object. Make sure to dispose 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
That is all for this demo.
Hope you find it helpful.