Batch File Send Email: Tutorial with Code Snippets [2024] (2024)

In the professional world, sending emails might just be the most commonly performed task. Whether it’s to contact a colleague, share information with a user, or achieve something completely different, emails serve as an essential element of communication.

Through the Simple Mail Transfer Protocol (SMTP), emails can be sent out using a range of tools, technologies, and methods.

One popular method involves batch files – script files in DOS, OS/2, and Microsoft Windows that have the .BAT or .CMD file extension.

In this article, we will go into detail on how to send emails using batch files, starting from file creation and going all the way to email delivery and testing.

So without further ado, let’s get right into it!

How to send emails using a batch file?

Step #1 – Create the file

Creating a batch file is quite an easy task as the only two things you need are a text editor and, well, knowledge of writing scripts consisting of commands. But no worries if you aren’t a pro at the latter; we’re going to help out :).

Now, to run those files, you need a command line.

A basic command line should already be part of your operating system, but if you want something more advanced, do install it before proceeding with the next steps.

Step #2 – Select an SMTP server

As mentioned in the introduction of this article, batch files send emails through the SMTP protocol. This means that you will have to include SMTP server credentials in your batch file script.

At your disposal is a range of SMTP servers, each with its own pros and cons, which you can explore on your own. But if you are looking for a recommendation from our side, then we have to mention Mailtrap Email API/SMTP Service.

Mailtrap SMTP

Mailtrap Email API/SMTP Service provides developers with a stable email infrastructure and effortless control over the same through dashboards with crucial email stats, weekly health checks, email logs, and critical deliverability alerts in case of any unexpected issues.

What’s more, Mailtrap Email API/SMTP Service will ensure high deliverability rates, and you can reach customer inboxes in seconds.

To retrieve the credentials for the SMTP server of this sending solution, you’ll need to get yourself a Mailtrap account.

Then just log in, add and verify your domain as described on the Sending Domain Setup page of the Mailtrap knowledgebase, and navigate to SMTP/API Settings under the Sending Domains page.

Batch File Send Email: Tutorial with Code Snippets [2024] (1)

Once you spot the SMTP credentials, save them in a convenient spot, as you’ll need them soon.

Try Mailtrap Today

Popular email clients and their SMTP servers

If, for whatever reason, you decide not to go with Mailtrap and instead want to use an SMTP server offered by an email client you are familiar with; you are absolutely free to. But do keep in mind that for each one, you will have to go through a somewhat unique account setup and credentials retrieval process.

To help you out with this, at least in terms of general settings, we created this table covering three popular mailbox providers and their SMTP servers.

Mailbox providersSMTP serverPortConnection
Gmailsmtp.gmail.com587, 25, 465TLS, SSL
Office 365smtp.office365.com587, 25TLS
Outlooksmtp-mail.outlook.com587, 25TLS

Step #3 – Select an email-sending tool and write the script

Although the command line is of crucial importance in the process we are describing, on its own, it’s not capable of delivering emails. For that, you’ll need a tool/program such as SendEmail.exe, BLAT, or PowerShell.

Sending with SendEmail.exe

SendEmail.exe is a tool that can be used in batch files to send emails from the command line. It was created to ease the running of Unix code with usr/lib/sendmail hardcoded as a means of email delivery.

To start using SendEmail.exe, download its file and extract it into a folder.

Then, open your command line and paste the following script with modifications made for parameters such as the sender, recipient, server, and so on:

<SendEmail.exe path> -f <sender> -t <recipient> -s <SMTP server>:[port] -xu <Authentication Username> -xp <Authentication Password> -o tls=no -u <Subject> -m <Message>

Script version with mock data:

C:\Users\user\Documents\sendEmail\sendEmail -f sender@example.com -t recipient@example.com -s send.smtp.mailtrap.io:2525 -xu **Authentication Username** -xp ****Authentication Password**** -o tls=no -u "Test email subject" -m "Test email content"

Once you run the script, your email should be delivered shortly!

Sending with BLAT

BLAT is a Windows command line utility for sending emails using SMTP. It is also capable of posting to Usenet through NNTP.

BLAT’s installation process is basically the same as SendEmail.exe’s, consisting of a .zip file download and extraction into a folder.

After installing the utility, you can use this script to send your email from the command line:

<blat.exe path> -body <Message> -u <Authentication Username> -pw <Authentication Password> -to <recipient> -f <sender> -charset utf-8 -s <Subject> -server <SMTP server> -port <Port>

Script version with mock data:

blat -body "Test email content" -u **Authentication Username** -pw ****Authentication Password**** -to "recipient@example.com" -f sender@example.com -charset utf-8 -s "Test email subject" -server send.smtp.mailtrap.io -port 2525

Note: BLAT struggles to work with specific SMTP servers such as Gmail. But, if your choice falls on Mailtrap’s SMTP, you won’t have any issues.

Sending with PowerShell

PowerShell, made up of a command-line shell, a scripting language, and a configuration management framework, is a solution for configuring systems and automating tasks.

As the solution can be used on Windows, Linux, and macOS, its installation process will depend on the OS you are using, according to Microsoft’s documentation.

To send an email with PowerShell and a batch file, you will have to complete a few steps.

First, in your command line, run @ECHO OFF. This will prevent batch file commands from displaying on the screen.

Then, call PowerShell and bypass the execution policy.

CALL :PowerShell CD /D C:\Windows\System32\WindowsPowerShell\v1.0 Powershell -ExecutionPolicy Bypass -Command "& '%CreateScript%'" EXIT 

To create your script and also check if a script by the same name already exists so it can be replaced, use the following commands:

:PowerShell SET CreateScript=%temp%\~tmpeScriptName.ps1 IF EXIST "%CreateScript%" DEL /Q /F "%CreateScript%"

Script version with mock data:

:PowerShellSET CreateScript=%temp%\~tmpTestScript.ps1IF EXIST "%CreateScript%" DEL /Q /F "%CreateScript%"

With your script created, you now need to send the output of your variables to it. This can be done by echoing said variable outputs as follows;

ECHO >> "%CreateScript%" ECHO $Username = "<username>" >> "%CreateScript%"ECHO $Password = "<password>" >> "%CreateScript%" ECHO $To = "test@test.com" >> "%CreateScript%" ECHO $From = "from@from.com" >> "%CreateScript%" ECHO $Subject = "<Email Subject>" >> "%CreateScript%"ECHO $Body = "<Email Body>" >> "%CreateScript%"ECHO $SMTPServer = "smtp.client.com" >> "%CreateScript%"

Script version with mock data:

ECHO >> "%CreateScript%"ECHO $Username = "**Authentication Username**" >> "%CreateScript%"ECHO $Password = "****Authentication Password****" >> "%CreateScript%"ECHO $EmailTo = "recipient@example.com" >> "%CreateScript%"ECHO $EmailFrom = "sender@example.com" >> "%CreateScript%"ECHO $Subject = "Test email subject" >> "%CreateScript%"ECHO $Body = "Test email content" >> "%CreateScript%"ECHO $SMTPServer = "send.smtp.mailtrap.io" >> "%CreateScript%"

The next step entails creating an SMTP client variable by calling the Net.Mail.SmtpClient function and passing it the SMTP server name and port as parameters.

ECHO $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 2525) >> "%CreateScript%"

For your newly-created SMTP client variable, you have to enable SSL and pass it the SMTP server credentials.

ECHO $SMTPClient.EnableSsl = $true >>"%CreateScript%"ECHO $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password) >>"%CreateScript%" 

Finally, by calling the Send method and passing it the sender and recipient email addresses, the subject, and the body, send off your email.

ECHO $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $Password) >>"%CreateScript%" ECHO $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body) >> "%CreateScript%" GOTO :EOF

How to send an email with an attachment using a batch file?

Even though sending emails with batch files seems quite basic, it does allow you to take things up a notch by adding attachments to the mix.

To demonstrate this, we will stick with using PowerShell for writing the script.

So, for the attachment you want to add, a variable needs to be created, and a file path has to be passed into its constructor.

ECHO $Mail = New-Object System.Net.Mail.MailMessage($EmailFrom, $EmailTo, $Subject, $Body) >> "%CreateScript%" ECHO $Attachment = New-Object System.Net.Mail.Attachment("<File-Path>") >> "%CreateScript%"

Script version with mock data:

ECHO $Attachment = New-Object System.Net.Mail.Attachment("C:\Users\user\Pictures\Screenshots\iphone.png") >> "%CreateScript%"

After doing that, you simply add the attachment variable to the email variable and call the Send method.

ECHO $Mail.Attachments.Add($Attachment) >> "%CreateScript%"ECHO $SMTPClient.Send($Mail) >> "%CreateScript%"

How to test emails sent with a batch file?

Whether you are using batch files or a very complex framework to send emails, testing should be done beforehand with the proper tools. Through testing, you get to preview your emails in different email clients, check if you are triggering spam filters, spot and fix errors in your HTML/CSS code, and much more.

And while you can do email testing manually in your personal inbox without any tools, in that case, you will be cluttering your inbox with junk mail, messing up your domain reputation, and lacking access to any advanced testing features. That is why we recommend going with something like Mailtrap Email Testing, an inseparable part of Mailtrap Email Delivery Platform.

When using Mailtrap Email Testing, you have no risk of spamming real recipients with testing emails, as this tool allows you to create virtual inboxes. It also has features for validating HTML/CSS, previewing content and analyzing it for spam, reporting on domain/IP blacklist presence, forwarding to whitelisted recipients, and gaining insight into detailed tech info.

Most importantly, testing your emails with Mailtrap is easy, all you have to do is:

  • Log into your Mailtrap account.
  • Navigate to Sandbox – > Inboxes – > SMTP Settings.
  • On the SMTP Settings page, click on Show Credentials to reveal the credentials.
Batch File Send Email: Tutorial with Code Snippets [2024] (2)
  • Take these credentials and include them in the part of your email-sending script shown below:
ECHO >> "%CreateScript%"ECHO $Username = "**Authentication Username**" >> "%CreateScript%"ECHO $Password = "****Authentication Password****" >> "%CreateScript%"ECHO $EmailTo = "recipient@example.com" >> "%CreateScript%"ECHO $EmailFrom = "sender@example.com" >> "%CreateScript%"ECHO $Subject = "Test email subject" >> "%CreateScript%"ECHO $Body = "Test email content" >> "%CreateScript%"ECHO $SMTPServer = "smtp.mailtrap.io" >> "%CreateScript%"ECHO $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 2525) >> "%CreateScript%"ECHO $SMTPClient.EnableSsl = $true >>"%CreateScript%"ECHO $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $Password) >>"%CreateScript%"ECHO $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $Password) >>"%CreateScript%" 
  • Run the full Powershell script, and your test email should land in your Email Sandbox virtual inbox in seconds!

Start Testing With Mailtrap

Wrapping up

For people new to this, sending emails using a batch file might sound like a joke as most expect the command line to only be used for making changes on our devices, not communicating with the “outside world”. But, thanks to tools such as Sendmail.exe, BLAT, and PowerShell, doing this proves to be very much possible.

That said, we hope you enjoyed reading this article and that it will aid you on your batch file email-sending journey!

For more email-related content, make sure to check out our blog where we cover topics like sending and testing emails/email notifications, deliverability, security, and more.

Batch File Send Email: Tutorial with Code Snippets [2024] (2024)

FAQs

How to create a .bat file to send an email? ›

Sending Emails Using Batch Files
  1. Step #1 – Create the file.
  2. Step #2 – Select an SMTP server. Mailtrap SMTP. Popular email clients and their SMTP servers.
  3. Step #3 – Select an email-sending tool and write the script. Sending with SendEmail.exe. Sending with BLAT. Sending with PowerShell.
Jan 9, 2024

How to automatically send email using JavaScript? ›

The simplest way to send an email from JavaScript is by utilizing the "mailto" protocol. It simply generates an email message with a pre−filled subject, recipient, and body. When a user clicks on a "mailto" link, it automatically opens their default email client with the pre−populated information.

How to send email via bash? ›

Mailtrap Email API
  1. Step 1: Copy your Mailtrap API token. Your API tokens are under Settings → API Tokens. ...
  2. Step 2: The Bash script. Make a POST request to the Mailtrap API. ...
  3. Step 3: Go to Email Logs. Navigate to Mailtrap Email Logs to see if sending was successful.
Feb 20, 2024

How to send mail from Linux with SMTP server? ›

How to Send Emails using Linux: In-Depth Guide
  1. The curl command.
  2. The mail command. Step 1: Install mail. Step 2: Postfix Configuration. Step 3: DB Files and Password. ...
  3. The mpack command. Step 1: Install mpack. Step 2: Create your email. Step 3: Attach files. ...
  4. The mutt command. Step 1: Install mutt. Step 2: Compose and send an email.
Jan 1, 2024

How to create a script to send mail? ›

Crafting a Shell Script to Send Emails
  1. Step 1: Define Script Parameters. Begin by defining the necessary parameters for your script, such as the recipient email address, subject, and message body. ...
  2. Step 2: Construct the Email Command. ...
  3. Step 3: Save and Execute the Script.
May 8, 2024

How do I write a .BAT file? ›

To create a batch file, open a text editor like Notepad and write your commands one line at a time. Save the file with a . bat extension, and you've created a batch file.

How can I automatically send emails? ›

On your computer, go to Gmail . At the top left, click Compose. Create your email. Click Schedule send.

Can you use JavaScript to send an email? ›

Can I send emails with JS or not? You can't send emails using JavaScript code alone due to the lack of support for server sockets. For this, you need a server-side language that talks to the SMTP server. You can use JS in conjunction with a server script that will send emails from the browser based on your requests.

How do I automatically send emails in Windows? ›

You can send automated emails using the Windows Task Scheduler,right-click Computer > Manage > Task Scheduler > Select Task/Event > RHS Pane > Create Basic Task > Follow wizard > in the Action step, check “Send an e-mail” option.

How to use SMTP JS to send email? ›

push({name : fileName, data : dataUri}) }; reader. readAsDataURL(file); }; Email. send({ Host : "smtp.elasticemail.com", Username : "OBSEM.submitRequest@gmail.com", Password : "***********", To : 'obsem.reportbug@gmail.com', From : "OBSEM.submitRequest@gmail.com", Subject : "Request from "+pseudo.

What is the syntax for send mail in Linux? ›

The mail command in Linux allows you to send emails directly from the terminal. It is used with the basic syntax: echo 'Body of Email' | mail -s 'Subject' recipientOfEmail .

What is the difference between sendmail and mailx? ›

in the end mailx uses sendmail to queue its mail for outbound delivery. the difference is mailx has a somewhat easier to use command line interface. Sounds like a DG Unix command line issue. sendmail isn't really designed for command line use (my opinion), but it can be done.

How to sendmail from command line? ›

Simple example

Once logged in, you can run the following command to send email: [server]$ /usr/sbin/sendmail youremail@example.com Subject: Test Send Mail Hello World control d (this key combination of control key and d will finish the email.)

How do I create an email file? ›

Save a message as a file on your computer or in the cloud
  1. Double-click to open the message you want to save, and on the File menu, click Save As.
  2. In the Save as dialog box, in the Folder pane, choose a folder, and then the location in that selected folder where you want to save the file.

How do you save a file as a bat? ›

Click File and then Save, and then navigate to where you want to save the file. For the file name, type test. bat and if your version of Windows has a Save as type option, choose All files, otherwise it saves as a text file. Once you have completed these steps, click the Save button and exit notepad.

How do I make a carbon copy email? ›

To add a CC recipient, click on the downward arrow on the top right corner in the To address box, as shown below. This will display the CC and BCC fields. In the CC field, enter the mail addresses of the recipients who'll receive a copy of the email. Compose your message and hit Send.

Top Articles
Latest Posts
Article information

Author: Lakeisha Bayer VM

Last Updated:

Views: 6002

Rating: 4.9 / 5 (49 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Lakeisha Bayer VM

Birthday: 1997-10-17

Address: Suite 835 34136 Adrian Mountains, Floydton, UT 81036

Phone: +3571527672278

Job: Manufacturing Agent

Hobby: Skimboarding, Photography, Roller skating, Knife making, Paintball, Embroidery, Gunsmithing

Introduction: My name is Lakeisha Bayer VM, I am a brainy, kind, enchanting, healthy, lovely, clean, witty person who loves writing and wants to share my knowledge and understanding with you.