How to send emails via the command line

Im not talking about a text-based email client that allows you to read and send mails on the terminal like Mutt here. In this article, I will show you a simple way to send emails via the command line.

The tools you will need are "msmtp" and " heirloom-mailx". These two are in the repository of most distros so you can install them easily. In Ubuntu-related distros, "heirloom-mailx" is installed by default so you just need "msmtp" then.

After got the two packages installed, you will need to create two config files to put in the home folder (or put in /etc/ if you want to use as root). The first one is .msmtprc. If you use Gmail like me, the .msmtprc file will look like this:
 account gmail   
 host smtp.gmail.com  
 port 587  
 protocol smtp  
 auth on  
 from Your Name  
 user username@gmail.com  
 password your-password  
 tls on  
 tls_nocertcheck  
 account default : gmail  

The second config file you need is .mailrc. Add the following line to .mailrc:
 set sendmail=/usr/bin/msmtp  

After creating the 2 config files, make the proper ownership for .msmtprc. Just open the terminal and run this command:
 chmod 600 .msmtprc  

How to send email from the command line:

- You can just open the terminal and run:
 mail emailadress@domain.com  

Then you enter the mail subject, then type the message, hit Enter for a new line. After finishing the message, just hit Enter then Ctrl + D to send the email:

How to send emails from the terminal

 - Another way to send email is to use with the command "echo". For example:
 echo "your message here" | mail email@adress.com  

- If you need to attach a file with the email, you can use the "-a" option:
 echo "your message here" | mail -a ~/Documents/some/file.rar email@adress.com  

- One trick you can use is create aliases for the mail addresses. You can create aliases in the .mailrc file like this:
 alias cat your_cute_cat@yahoo.com  
 alias dog your.ugly.dog@hotmail.com  
 alias hamster nice.hamster@xhamster.com  

After you create aliases in the .mailrc file, you can just send an email like this:
 echo "hello my cat" | mail cat  

Note: When this method is quite fast and convenient to send emails, one disadvantage is that your email password is shown in the .msmtprc file. So consider about your security first.
linux tips and tricks