Sending Mail from Bash

Patrick Gichini
MindNinja
Published in
2 min readApr 9, 2019

Bash is a UNIX shell and command language.

Bash runs on a text window where users type commands that cause actions. Bash can also read commands from a file which is usually called a bash scripts. These bash scripts can be used to perform a variety of operations and actions on Linux.

The beautiful thing about bash is that it is super easy to run and apply to your daily tasks.

Enough talk, let’s get dirty,

As an introduction to bash, we are going to write a script that allows us to send an email.

Simply open up your terminal and create a new file. You can name it bash. Now you’ll find that most people use a .sh extension which is not really a problem although it has its disadvantages when it comes to flexibility. For this article, it doesn’t matter whether you use the .sh extension o not.

After creating the file, you have to open it and start with the shebang. This is vital in order to make the script executable. This is how you write the shebang:

#!/bin/bash

After that, enter the lines below:

from="user1@gmail.com"
to="user2@gmail.com"
subject="Howdy!"
message="Aaaaaah! I can send an email with bash!"
mail -s "$subject" -r "$from" "$to" <<< "$message"

The from and to variable defines your source and destination email addresses. You also define the subject and message in respective variables.

The mail command is the line that actually sends the email and uses the contents of those defined variables.

The whole code including the shebang should be:

You should receive an email on your defined email address with the defined subject and message.

Have fun!

Enjoyed this article, you can follow MindNinja and get access to this and more exciting articles about coding, science, data and more fun stuff. Also don’t forget to leave a clap. Thanks for reading!

--

--

Patrick Gichini
MindNinja

Linux Ninja | Data Enthusiast | Sentimental Poet | Agent Boyfriend