How to Send Email in Bash? [2 Methods]

To send email in Bash, first, you need to generate app-specific password and set up an SMTP server on your machine. Then you can use different available commands to send emails directly from the command line. However, there are various commands to send email in Bash. In this article, you’ll explore how to leverage 2 different methods in Bash to send emails efficiently.

Environment Setup for Sending Email in Bash

Before creating a script for sending emails in Bash, you have to generate an app-specific password and set SMTP. Follow the steps below:

Step 1: Generate App-Specific Password

Follow the steps below to generate a password that is specific to an application in Gmail:

  1. Follow 2FA documentation to enable 2FA on Gmail.
  2. Once you have 2FA enabled, visit this site to generate an app-specific password.
  3. After logging in to your account, you can see the following window. Select Mail from the Select app dropdown list as follows.

    Selecting Mail for generating app specific password

  4. From the Select device dropdown list, select Other (Custom name) option.

    Selecting Custom name to give a name of the device

  5. Now give the name of the device. You can give something memorable as I named it mailx (Ubuntu) in this case. Finally, click on Generate to create the app-specific password.

    Giving the name of the device

    A password of 16-character is given just after the click. The following image shows the generated app-specific password.

    Get the app specific password to send email in Bash

At this point, you have obtained an app-specific password from your E-mail provider. In the subsequent steps, I will show you how to set up an SMTP server and then send mail.

Step 2: SMTP Server Set-up

Follow the steps below to configure a SMTP (Simple Mail Transfer Protocol) server on your Linux:

  1. At the beginning, open the system (Ubuntu) terminal and run the command below to successfully install the mailx and necessary packages to set up a SMTP server.

    sudo apt-get install mailutils

    Installing mailx command to "send email in Bash"

  2. Press “Y” to continue the installation.Giving confirmation for installation
  3. After installation it automatically opens the Postfix Configuration window. Select Ok, then press the right arrow and press on ENTER to continue configuring the package.Continue to configure mailx
  4. At this point of configuration select Internet Site and continue with Ok.Select Internet Site and continue
  5. Change the System mail name as your wish and continue with Ok. This will successfully install the necessary packages.Change mail name
  6. If you run the installation command again you will see a message that mailx is already installed in the system. Now, it’s time to configure the /etc/ssmtp/ssmtp.conf file.Check the installation of mailx
  7. To open the SMTP configuration file run the command below:
    sudo nano /etc/ssmtp/ssmtp.conf
    Note: The above command can’t open the configuration file if smtp is not installed in the system. Run the command below to install smtp at this stage:
    sudo apt-get install ssmtp
  8. Now change the configuration file as follows.Change the configuration file to send email.Change the configuration file to send emailLet us understand the meaning of each field I changed in the configuration file.
    EXPLANATION
    • SERVER: This field indicates from sender email ID.
    • mailhub: This field indicates where the mail goes. If you are using Google’s e-mail services, we assume that this goes to Google’s e-mail server. In that case, this should be gmail.com. If your e-mail service provider is not Google, you should go through the documentation of your e-mail provider.
    • AuthUser: This is the field where you enter your e-mail address. If, for example, my e-mail address is [email protected], I would enter this address in the AuthUser
    • AuthPass: You have to place the 16-character long alphanumeric app specific password in this field. The password I generated is tdthrcmigwfduiow (there are no spaces).
    • UseTLS: This uses the TLS protocol to wrap the SMTP contents that enable you to send encrypted e-mail. The recommended value of this field is “YES“.
    • UseSTARTTLS: This specifies if the STARTTLS should be used or not. I would recommend you use STARTTLS and fill the field with “YES“.
    • rewriteDomain: It should be the domain that can rewrite your mail. Gmail is the rewrite domain in my case.
    • Hostname: You can leave the field as it is or change it to your mail ID.
    • FromLineOverride: This field specifies whether you are allowed to override the ‘From header‘ of an e-mail or not. I fill the field with “YES”.

2 Methods to Send Email from Bash Terminal

Sending emails from a Bash terminal is an efficient way to automate notifications, reports, or alerts. Here are the two popular methods for accomplishing this task using the mailx and curl commands:

1. Using “malix” Command

The mailx is a versatile command-line utility for sending and receiving emails. It’s commonly available on Unix-based systems and offers a simple syntax for sending emails directly from the terminal. Here’s how to use this command to send emails form Bash terminal:

  1. Firstly, write the following command to open a mailx.sh file in the build-in nano editor:
    nano mailx.sh
  2. Copy the following script and paste it into nano. Press CTRL+O and ENTER to save the file; CTRL+X to exit. Alternatively, copy the following script. Paste the script in a text editor and save it as .sh file.

    #!/bin/bash
    
    recipient="[email protected]"
    subject="Leave"
    
    body="I would like to request you for next two days leave.\\n
    \\
    n
    Regards
    Laku"
    echo -E "$body" | mailx -s "$subject" "$recipient"
    EXPLANATION

    The provided Bash script demonstrates a simple example of sending an email using the mailx command. The script sets the recipient’s email address, subject and body of the email. Then, it pipes the body content to the mailx command with the specified subject and recipient address.

  3. Now, Use the following command to make the file executable:
    chmod u+x mailx.sh
  4. Finally, Run the script by the following command:
    ./mailx.sh

When executed, this script will send an email to the recipient ([email protected]) with the subject “Leave” and the given body text.

Also, you can use malix <recipient> structure:

Mailing from terminal

2. Using CURL Command

The curl is a powerful command-line tool for transferring data with URLs. When paired with SMTP  servers, it can be used to send emails programmatically from the terminal. Here’s the script:

#!usr/bin/env bash

# User input
read -p "Enter your email : " sender
read -p "Enter recipient email : " receiver
read -p "Enter your Google App password : " gapp
read -p "Enter the subject of mail : " sub

echo "Enter the body of mail : "
read -r body # using read command for multiline input

# curl command for accessing the smtp server
curl -s --url 'smtps://smtp.gmail.com:465' --ssl-reqd \
--mail-from "$sender" \
--mail-rcpt "$receiver" \
--user "$sender:$gapp" \
--mail-rcpt "$receiver" \
-T <(echo -e "From: ${sender}\nTo: ${receiver}\nSubject: ${sub}\n\n${body}")

This script captures user input for sender email, recipient email, Google App password, and email subject. It then prompts the user to input the email body. The script utilizes the curl command to send the email via SMTP to the recipient using Gmail’s SMTP server.

How to Attach a File with Email from Bash Terminal?

Attaching a file to an email from the Bash terminal can be achieved using the curl command with SMTP. Here’s a step-by-step guide on how to do it:

#!/usr/bin/env bash

# User input
read -p "Enter your email: " sender
read -p "Enter recipient email: " receiver
read -p "Enter your Google App password: " gapp
read -p "Enter the subject of mail: " sub
read -p "Enter path to the file to attach: " attachment

# MIME type for the attachment
MIMEType=$(file --mime-type -b "$attachment")

# curl command to send email with attachment
curl -s --url 'smtps://smtp.gmail.com:465' --ssl-reqd \
--mail-from "$sender" \
--mail-rcpt "$receiver" \
--user "$sender:$gapp" \
-F "=(;type=multipart/mixed" \
-F "=$body;type=text/plain" \
-F "file=@$attachment;type=$MIMEType;encoder=base64" \
-F "=)"

Make sure to replace the SMTP server address, port, and any authentication credentials with your own if you’re not using Gmail’s SMTP server. Additionally, ensure that the file path provided for the attachment is correct.

Conclusion

In conclusion, sending emails from the system terminal or creating a Bash script for sending emails is not a straightforward task. However, once you send your first email from the command line, you will be a pro in sending emails with Bash.

People Also Ask

How to send emails from Linux terminal?

To send emails from the Linux terminal, use malix command in the below syntax:

echo "Message body" | mailx -s "Subject" [email protected]

Replace “Message body”, “Subject”, and [email protected] with your desired content.

How to send emails with multiple recipients in Bash?

To send emails to multiple recipients using mailx command, add the recipients’ mail one after one delimited by comma.

How to preserve whitespaces while sending emails using mailx command?

To preserve whitespace, including newlines, when sending emails using the mailx command in Bash, you can use the -E option. This option ensures that the body of the email is sent to the recipients without any modifications.

How can I check whether my emails are delivered or not?

To check whether your emails are sent or not, use the $? variable to check the exit status of the previously executed command. Here’s how you can check the exit status of the mail command in Bash:

mail -s "Subject" [email protected] <<< "Message body"
# Check exit status of the mail command
if [ $? -eq 0 ]; then
echo "Email sent successfully."
else
echo "Failed to send email."
fi

Related Articles


<< Go Back to Bash Script Examples | Bash Scripting Basics | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

Leave a Comment