Send Email with attachment using SharePoint PowerShell


Posted on : Tue, 11th Aug 15 05:09 pm UTC
100+ votes

How to send email with attachment from PowerShell using SMTP

Below is a code snippet to send an email with an attachment from SharePoint server using PowerShell script. The attachment can be referred to any location or generated from the script itself.
The below code can be modified to change SMTP Server, From and To Email address, Subject, Body, Attachment and other parameters.

Name : Send email with attachment via PowerShell
  
# File to be attached in email
$attachment = new-object Net.Mail.Attachment("[FILE PATH]")

# Configure SMTP server
$smtpServer = "[SMTP SERVER]"
$mailMessage = new-object Net.Mail.MailMessage
$smtpObj = new-object Net.Mail.SmtpClient($smtpServer)

# Set email parameters
$mailMessage.From = "[FROM EMAIL ADDRESS]"
$mailMessage.ReplyTo = "[REPLY TO EMAIL ADDRESS]"
$mailMessage.To.Add("[TO EMAIL ADDRESS 1]")
$mailMessage.To.Add("[TO EMAIL ADDRESS 2]")
$mailMessage.subject = "[MAIL SUBJECT]"
$mailMessage.body = "[MAIL BODY]"
$mailMessage.Attachments.Add($attachment)

# Send email
$smtpObj.Send($mailMessage)
$attachment.Dispose()
  

The attachment can be any kind of file, but take care of few points -
- File path exists
- Firewall is not blocking file type
- Size of file is within allowed limits

If you want to add more recipients, just add another entry for $mailMessage.To.Add("[TO EMAIL ADDRESS]").

Code2care's mission is to share varied knowledge in technical and non-technical areas gathered during day-to-day learnings and development activities so that our visitors can leverage this portal to find solutions to their queries without re-inventing the wheel. Technical posts include Learnings, Tutorials, Video Tutorials, Code Snippets, Tips-n-tricks.

Follow us : Facebook - Twitter - Google +