Home > .NET, PowerShell > Sending Email With Attachments In PowerShell

Sending Email With Attachments In PowerShell

January 19th, 2010

Here's an example on how to send email with attachments via PowerShell:

POWERSHELL:
  1. # A Mailer script that makes use of System.Net to send email with attachments
  2. #
  3. # Sample usage:
  4. #  PS C:\> Send-Mail-With-Attachment 'email@domain.com' 'Hello world!' 'Filename.txt'
  5.  
  6. function global:Send-Mail-With-Attachment($to, $subject, $file){
  7.  
  8.   $filenameAndPath = (Resolve-Path .\$file).ToString()
  9.   $from = 'Automated Powershell Mailer'
  10.  
  11.   [void][Reflection.Assembly]::LoadWithPartialName('System.Net') | out-null
  12.  
  13.   $message = New-Object System.Net.Mail.MailMessage($from, $to, $subject, $subject)
  14.   $attachment = New-Object System.Net.Mail.Attachment($filenameAndPath, 'text/plain')
  15.   $message.Attachments.Add($attachment)
  16.  
  17.   $smtpClient = New-Object System.Net.Mail.SmtpClient
  18.   $smtpClient.host = 'mail.domain.com'
  19.   $smtpClient.Send($message)
  20. }

Contribute, view, or download the script here: Mailer.ps1

Author: Adam Kahtava Categories: .NET, PowerShell Tags:
  1. No comments yet.
  1. No trackbacks yet.