Purpose: In one our previous post we saw how to send emails using shell script. In this blog post we will extend that concept and see how we can send attachments also along with the email body message in just one command from shell script using our familiar mail command.

Step 1: Prepare your e-mail body message

cd;
nano message.txt

and enter some text which will be the body of the email:
Hi,
This is a test message to see if you are getting my attachment and this message in the email.

Save and quit the file.

Step 2: Select your attachment

Let’s say you want to send a file called project.txt which is residing in your home directory:

myserver:~$ ls /home/kushalk
message.txt  project.txt

Step 3: Send the email

The following single command will enable you to send an email using the mail command with the message from Step 1 and the attachment from Step 2:

(cat message.txt; uuencode project.txt project) | mail -a "From: sender@abc.com" -s "My Subject" reciever@abc.com

Where:

message.txt = Email’s body message

project.txt = File that you want to send as an attachment

project = Final destination name of the above project.txt file that will be sent in the mail. You can also type project.txt itself the final destination name.

“From: sender@abc.com” = The From field of email message will be populated with the sender@abc.com which basically is the sender of the email

“My Subject” = Subject of the email

receiver@abc.com = To whom you would like to send the email to

That’s it!

Happy Emailing!

Be Sociable, Share!