Menu Close

How To Send Emails With Attachment From Powershell [2020]

Today I’m going to show you how to send emails with attachment from Powershell. Many organizations have SMTP servers to trigger emails from an application server to recipients. What admins normally do when a user reports an issue that emails aren’t being delivered from a server.

They’d most likely request them to try the telnet test to validate the mail flow. Of course, telnet works to verify mails but it doesn’t support emails with attachment and its a lengthy process to follow. Therefore, I would suggest that try sending an email using the PowerShell script as it is the easiest and effective method to perform.

$fromaddress = This is the sender email address
$toaddress = This is the recipient email address
$Subject = Subject of an email
$body = Make an HTML for an email body
$attachment = This is the location of an attachment file
$smtpserver = “SMTP SERVER NAME HERE”

Here is the full script how to send emails with an attachment from PowerShell

#####Define Variables#####

$fromaddress = “admin@techieberry.com”
$toaddress = “user@techieberry.com”
$Subject = “Email Attachment Test”
$body = get-content “C:\users\desktop\content.html”
$attachment = “C:\users\desktop\test123.txt”
$smtpserver = “SMTP SERVER NAME HERE”

##################################

$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$smtp.Send($message)

####################################################

How to execute the script?

  • Make sure you installed a latest Windows Powershell
  • Copy the script
  • Paste it on a notepad file
  • Save it as filename.ps1
  • Access “Windows PowerShell
  • Go to the location of a saved file and execute them.
  • If you face any error in above steps, right-click the .ps1 file, Click “Edit” and press F5 key to execute the same.

Screenshot of the script is below.

how to send emails with attachment from PowerShell

As you can see, this is easy to follow and more importantly, emails receive faster when they send from the PowerShell.

Want to improve your Exchange Online experience for better productivity? Check out the tips and tricks mentioned here.

Now I’d like to hear from you:

Did I Miss Anything? Maybe you have a question about something that I covered.

Either way, I’d like to hear from you. So go ahead and leave a comment below.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *