Wednesday 13 January 2021

Windows Batch/Powershell Script to Send EMail with Attachments

Automatic Mail Sending through Batch/Powershell Scripting on Windows

This guide is for those who are looking for the simplest way to trigger mails from their Windows Servers along with attachments (if required). The same mechanism can be configured with Task Scheduler to trigger it on regular intervals OR whenever you want it to run.

The whole concept requires 2 different scripts,

1) BAT file

2) Powershell Script

The below example I have used is for getting the status for Task Scheduler Jobs and send them over mail. But you can configure the script do get whatever info you want & push it through mail.

Note: The script required SMTP details to work so make sure you are having one already configured with you :)

Let's begin...

Now open a notepad, paste the below code & alter it w.r.t your requirement,

Param([String]$xVariable)

$smtp = "SMTP@domain.com"

$to = "recepient1@domain.com","recepient2@domain.com"

$from = "sender@domain.com" 

$subject = "Mail Title" 

$body = "Your Content"

$attachment="Path\FileName"

send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Attachments $attachment -Priority high

Save it with any name but put extension as .ps1 (that means it's a powershell script)

If you want to have multiple lines in your Mail Body, you can add them like,

$body = "First Line"+"<br>"+"Second Line"

Now open more notepad and paste the below lines of Code,

@echo off

schtasks /query | find /I "string"  > path\filename

C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe path\filename.ps1

Now save this as .BAT extension with any name you want.

At this point you are all set to capture the SCHTASKS output to a file & send it over mail to anyone you want.

No comments:

Post a Comment