User Input
We will first input the requirements from the input, these will be sender email, receiver email, google app password, subject, body, and attachments if any. So it’s quite simple to take input in BASH We’ll use the read command along with the -p as an argument to prompt the user with an info message prompt for better understanding.
#!usr/bin/env bash # Input for sender email read -p "Enter your email : " sender # Input for recipient email read -p "Enter recipient email : " receiver # Input for google app password read -p "Enter your Google App password : " gapp # Input for subject of the mail read -p "Enter the subject of mail : " sub
Taking input of body text in a file
So the sender email, receiver email, google app password, and the subject are taken care of but how we will input the body and the attachment. Well, for that we will use the cat command to first input into a file and copy all the content from that file into a variable like this:
# Using cat command to input multiline text to a variable (from file) echo "Enter the body of mail : " cat > tempfile.txt body=$(cat tempfile.txt)
The cat command used with > can redirect the inputs to the file provided after the operator. You have to press CTRL + D to save the multi-line content which you have written and to quit from the cat command. Finally, we store the output of the cat command to a variable. We have used the cat command both ways to write to the file and also for reading from the file. Thus, we have the body variable to work with later.
Adding an attachment file
Now comes the attachment part, we need to provide the positional argument as the file name to specify the attached file.
# set file variable to the 1st positional parameter file="$1" # MIME type for multiple type of input file extensions MIMEType=`file --mime-type "$file" | sed 's/.*: //'`
This will store the name of the file and next, we will also need the type of file. we are extracting the file extension or its type from using the mime fields in the file. We are piping the filename with the set editor and filtering the text after the ‘:’ in the output of the file command. The demonstration of the code is shown below:
So, the filename is stored in the file variable and the filetype is stored in the MIMEType variable. After this, we move on to the cURL command.
Send mails using a Bash Script
Sending email via the command line can be quite a great feature to have especially on Linux which will allow some users to avoid using the GUI and installing all of the dependencies. We will look into the following article on how to write a BASH (shell) script that can send a custom email to any other email using the SMTP server.