[How To] Send mail with attachment from Unix shell

[Unix] Send mail with attachment from Command Prompt

This article shows how to send e-mails from a shell script, including file attachments, subject line and e-mail body. The following tutorial applies to Linux as is.

There are two ways to do this, first is the interactive mode where the terminal asks for Subject and Mail body interactively. Second ways is to provide all these options directly at one go.

Interactive Mode:
$ mail -a attachment.txt email@server.com

One you type in the above command, the terminal will ask for below input
Subject:

Once you enter the Subject the message body begins. Type in the message body and press ctrl+d. This signifies End Of Transmission, EOT. This way, the terminal will send a mail with the mail with subject line and attachment.txt to the recipient email@server.com.

Direct Command:
$ echo "This is a test mail" | mail email@server.com -s "test mail" -a attachment.txt email@server.com

The above command will send a mail to email@server.com with subject "test mail" and mail body as "This is a test mail". Also, attachment.txt will be sent as attachment file.