PowerShell Automation: How to Send Email
While developing some of the automation tools it was required to send emails to the intended users sometimes to inform them about the operational progress or otherwise.
In this article, we 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 we have shown the distribution list comprising of intended participants, here in this article we choose to make it hardcoded within the code which is an absolutely bad idea J and should be avoided. Rather we should have an 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.
https://howtodowithsharepoint.files.wordpress.com/2017/06/15.png?w=863&h=226
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 step, 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-
https://howtodowithsharepoint.files.wordpress.com/2017/06/2.png?w=800
That’s all for the code.
On successful execution, we will get a new email in the Inbox as shown below
https://howtodowithsharepoint.files.wordpress.com/2017/06/31.png?w=800
That is all for this simple demo.
Hope you find it helpful.