How to send an email with Bash

Sending emails directly from a Linux terminal using Bash can be useful in many contexts, such as automating notifications or managing system scripts. In this article, we will explore the most common methods to do so.

Prerequisites

Before you begin, make sure you have access to:

  • A Linux terminal.
  • A configured SMTP server or an installed email client (e.g., sendmail, mailutils, or ssmtp).

Method 1: Using the mail command

The mail command is a simple tool for sending emails. You can install it with:

sudo apt-get install mailutils

To send an email, use the command:

echo "Message" | mail -s "Subject" recipient@example.com

Here, "Message" is the body text, "Subject" is the email title, and recipient@example.com is the recipient's email address.

Method 2: Using sendmail

sendmail is another popular tool. You can send emails by creating a complete message with headers. Example:

sendmail recipient@example.com << EOF
Subject: Subject

Message body
EOF

Ensure that sendmail is properly installed and configured.

Method 3: Using ssmtp

ssmtp is useful for setting up an SMTP server and sending emails with simplicity. After installation, edit the configuration file /etc/ssmtp/ssmtp.conf to add your SMTP server credentials.

An example command to send an email is:

echo -e "Subject: Subject\n\nMessage" | ssmtp recipient@example.com

Automating with Bash

You can automate email sending by placing the commands into a Bash script. Example:

#!/bin/bash

TO="recipient@example.com"
SUBJECT="Subject"
MESSAGE="Message body"

# Using the mail command
echo "$MESSAGE" | mail -s "$SUBJECT" "$TO"

Save the script, make it executable with chmod +x script.sh, and run it with ./script.sh.

Conclusion

Sending emails with Bash is an essential skill for anyone working on Linux systems. Choose the tool that best fits your needs and consider security, especially when using credentials or SMTP servers.

Back to top