Send Email via Gmail SMTP Cmd Line

General Information

Send an e-mail message from a bash script or command line program.


  • Distro(s): Debian/Ubuntu based

This package will allow you to configure what gmail account to send from and will connect securely via TLS to the gmail SMTP servers.

sudo apt-get install msmtp-mta

Install a simple mail transfer agent to actually prepare the e-mail message.

sudo apt-get install heirloom-mailx

1) Create a file in your home directory called “.msmtprc”

vim ~/.msmtprc

2) Paste the following into the config file, change the “your_address” x2 and “your_gmail_password” to refect your information:

#Gmail account
logfile ~/msmtp.log
account gmail
auth on
auth on
tls on
tls_trust_file /usr/share/ca-certificates/mozilla/Equifax_Secure_CA.crt
password your_gmail_password
port 587
account default : gmail

Note: If you use two factor authentication for gmail, you will need to create an application specific password for this config file. To do that:

  • Login to Gmail
  • Click your Account Icon (top right), then Account
  • Click on the Security tab on the top
  • In the “Sign-in” box, accross from App Passwords, click on Settings.
  • Select a custom name and type something to describe msmtp so you won't forget what it is for.
  • Click Generate
  • Copy and paste the password from the pop up box into the config file above as “your_gmail_password”

3) Secure the config file Since it contains credentials, ensure only you can read it:

chmod 600 .msmtprc

Setup mailx to use msmtp to send e-mail.

Create a .mailrc in your home folder:

vim ~/.mailrc

Paste the following in:

set sendmail="/usr/bin/msmtp"
set message-sendmail-extra-arguments="-a gmail"

mail -s "Subject Here"

You will now be able to type in your message. When you want to send it, type ENTER to go to a blank line and then Ctrl+D to end/send.

To send an e-mail from a script, you will need to pre-write your message.

Populate a text file, such as “message.txt” with the e-mail to be sent. Then, send it like this:

mail -s "My Awesome Message Subject" < message.txt
  • linux_wiki/send_email_via_gmail_smtp_cmd_line.txt
  • Last modified: 2019/05/25 23:50
  • (external edit)