How to send a file as an email attachment using the Linux command line?

LinuxOperating SystemOpen Source

In order to send a file as an attachment to an email using Linux, we either need to make use of a command line email client or the standard linux mail command.

There are multiple command line email clients available to achieve the attachment task, but the most common and widely used is mutt.

Mutt is a command line based email client that allows us to send and read emails from command line in Linux based systems. It also supports important protocols like IMAP and POP which broadens the use-cases and application of mutt.

Some of the key features that Mutt has are −

  • Easy to configure and install

  • Allows us to send attachments with emails

  • Allows message threading

  • Supports multiple languages.

In order to make use of mutt, we first need to install it on our local systems.

Consider the commands shown below for different versions that will help in installing mutt on the local machine.

For Linux Based Systems −

apt-get install mutt

For Centos/Fedora Systems −

yum install mutt

For Mac OS −

brew install mutt

Now once the mutt is installed we just need to write the following command to the terminal, and our mail along with the attachment will be sent to the email id.

echo "Message Body" | mutt -a "/file_to_attach" -s "subject of the message" --
recipient@domain.com

Let’s break down the above command to understand it better, the mutt keyword is used to specify that we are making use of mutt email based client, followed by the -a flag which is used to denote that we are attaching some file along with the email which is followed by the path to that file, then we have a -s flag that is used to tell mutt that we are providing a subject for the email and lastly we have the email id to which we want to send the email.

One alternate way is to make use of the mail command utility that Linux provides us with.

Just write the following command to the terminal, and you will get the same result as the mutt command.

Output

mail -s "Backup" -a mysqldbbackup.sql sample@email.com < mail-message.txt

We can either make use of the mail command utility or the mutt email client, both will work fine. It just so happens that the mutt email client offers more features and services.

raja
Published on 29-Jul-2021 11:31:52
Advertisements