Powershell Function to send email

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.

  • December 22, 2022