web stats

Sending Mail Through the Command Line

t’s pretty annoying having to load up Thunderbird every time I want to send an email. It’s supper clunky to manoeuvre when all you want to do is send plain text over the internet.

Well, not only can the mail command send mail locally (from user to user) but it can send it by relaying it through another server. That is, you can relay email through your email provider – send emails from the command line!

I followed this guide but here it is in short.

1) You need to configure postfix. Go do that first. Make sure you can send messages from user to user (local messages). The Arch Wiki has a good guide on it.

2) Add these lines to your /etc/postfix/main.cf

relayhost = [smtp.gmail.com]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_CAfile = /etc/postfix/cacert.pem
smtp_use_tls = yes

Basically this is telling postfix to relay external messages through gmail. It also says that your password and username is stored at /etc/postfix/sasl_passwd.

3) Now you need to actually put your username and password at /etc/postfix/sasl_passwd.

Code:
[smtp.gmail.com]:587    [email protected]:password

Make sure you make it so that only root can read it:

Code:
# chown root:root /etc/postfix/sasl_passwd
# chmod a-rwx /etc/postfix/sasl_passwd
# chmod u+r /etc/postfix/sasl_passwd

chown root:root changes the owner:group of the file.
chmod a-rwx removes read/write/executable permissions from all users
chmod u+r adds read permissions to the owner of the file (root)

Alternatively you could have just typed

Code:
# chmod 400 /etc/postfix/sasl_passwd

Which is octal for the nine binary bits of the permissions header. I.e:
400 = 100 000 000 = r– — —
The first three are the owner permissions, the second three are the group permissions and the last three are everyone else (other) permissions. You already knew this though, right?

4) Format it for postfix:

Code:
# postmap /etc/postfix/sasl_passwd

5) Copy the template certificate into postfix so that gmail can read it:

Code:
# cp /etc/ssl/certs/Thawte_Premium_Server_CA.pem /etc/postfix/cacert.pem

Restart postfix and we’re done. Sending mail is as simple as:

Code:
$ mail -s "Important Subject!" [email protected]
HAI
BAI

Ctrl+d to end and send the message. You can even pipe messages into it!

Code:
$ printf "OH HAI!\n" | mail -s "Important Subject!" [email protected]

I use this to let me know when things happen like my backup finishes or when deadlines with scripts called from crontab or whatever.

Cool.

Discuss http://www.totse.info/bbs/showthread.php?t=13389

Leave a Reply