Powershell function to send emails

I often write, powershell scripts to either run in background or run via sql job. In either case, I sometimes like to have some sort of email notification send out either on success or failure. Powershell allows you to send email from within the code. Even thought it is usually few lines of code to write and it is quick, I prefer to remember one line and something I can recall top of my head. Therefore, I created a function and include in my custom powershell module so next time if I need to send an email. I can call this function.

I hope this will help some one out there. If you do not know how to create powershell module, I will soon be posting an article on it.

Function Send-Email { param( [parameter(Mandatory)] [string]$mailFrom , [parameter(Mandatory)] [string[]]$mailTo , [parameter(Mandatory)] [string]$mailSubject , [string]$mailBody , [string]$mailAttachment ) $smtpServer="email.mysmtpserver.com" $msg = new-object Net.Mail.MailMessage $smtp = new-object Net.Mail.SmtpClient($smtpServer) $att =new-object Net.Mail.Attachment($mailAttachment) $msg.From = $mailFrom $msg.To.Add($mailTo) $msg.Subject = $mailSubject $msg.Body = $mailBody $msg.Attachments.Add($att) $smtp.Send($msg) $att.Dispose() }

If you would like more powershell scripts like these, send me an email and I will do my best to post more stuff.

Originally published at https://blog.sanchitwadhwa.com on December 22, 2022.

--

--

I help solve data problems |Need help ? email me > imsunchip@gmail.com | website > sanchitwadhwa.com | ❤ Books, music, dance, food, podcasts, soccer, writing

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sanchit Wadhwa

I help solve data problems |Need help ? email me > imsunchip@gmail.com | website > sanchitwadhwa.com | ❤ Books, music, dance, food, podcasts, soccer, writing