PowerShell: Email a log file

PowerShell has access to the complete .NET Framework, so the easiest way to send an email is just the way you would do it in .NET, using the System.Net.Mail.SmtpClient class.

You can do it as simply as this:

$smtp = new-object Net.Mail.SmtpClient(”localhost”)
$smtp.Send(”from@yourdomain.com”, “recipient@theirdomain.com”, “subject here”, “body here”)

If you want more control over the message contents, you can use the System.Net.Mail.MailMessage class and send that instead.

$filename = “logfile.txt”
$smtpServer = “localhost”

$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($filename)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)

$msg.From = “somebody@yourdomain.com”
$msg.To.Add(”somebody@theirdomain.com”)
$msg.Subject = “Nightly Log File”
$msg.Body = “The nightly log file is attached”
$msg.Attachments.Add($att)

$smtp.Send($msg)

Thanks to the PowerShell Guy /\/\o\/\/Sending Mail from MSH!

2 Comments

  1. Posted October 11, 2008 at 1:15 am | Permalink

    You will also need to close the attachment after sending it using $att.dispose() otherwise the file will remain locked….

    http://teckinfo.blogspot.com/2008/10/powershell-email-locks-attachment.html

  2. Anwar
    Posted April 5, 2009 at 8:26 am | Permalink

    Just watch out if the log file is large file and consider your enviroment policy for sending large email. Maybe you may want to test the size of the file first, if it is bigger than allowed size then throw a link rather attach it..


One Trackback

  1. [...] point me in the right direction? > > Thanks, > > Matt Duguid Maybe this will help: http://ozgrant.com/2007/07/25/powers…il-a-log-file/ Marco — Microsoft MVP – Windows PowerShell http://www.microsoft.com/mvp PowerGadgets MVP [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*