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 email@example.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:
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:
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:
- Another way to send email is to use with the command "echo". For example:
echo "your message here" | mail firstname.lastname@example.org
- 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@example.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 firstname.lastname@example.org alias dog email@example.com alias hamster firstname.lastname@example.org
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.