While developing some of the automation tools I was required to send emails to the intended users sometimes to inform them about the operational progress or otherwise.
In this article I will take you through the steps to develop PowerShell functions that can send emails to the intended participants.
Let’s look into the code base used for this article-
Step – 1: This will be the final step where we are calling the “Send-Email” function, implementation of which can be seen in the upcoming steps.
Step – 2: In this step I have shown the distribution list comprising of intended participants, here in this article I choose to make it hard coded with in the code which is an absolutely bad idea J and should be avoided. Rather we should have external content source (CSVs, SharePoint Lists) to configure this list of intended recipients.
Step – 3: In this step we have declared a variable holding subject for the email
Step – 4: In this step we prepare the body of the email. It is worth noting that you can use any valid HTML to prepare the mail body. Make sure you don’t use CSS Classes as they won’t work here. You can use inline styles to format the html.
Step – 5: In this step we will call the helper function and pass on the data we have prepared in previous steps. This function has the responsibility to send the email to the required recipients.
Step – 6: In this step we get the Sender’s Id. As a part of the best practice this should be a generic Id.
Step – 7: In this we get SMTP Server Address to relay through the mail
Step – 8: In this step we are creating the array of recipient since “Send-MailMessage” function uses Array as parameter return type to “-To” parameter.
Step – 9: In this step we are calling “Send-MailMessage” function by passing required parameters as shown below-
That’s all for the code.
On successful execution we will get a new email in the Inbox as shown below-
That is all for this simple demo.
Hope you find it helpful.