Saturday, March 26, 2016

Set up your linux system to send emails with a Gmail account

Because many programs rely on the local mail server UNIX systems come with to send emails, or because you don't want to put your Google password in config files on your web server, or for any other reason, then you are going to need to use an Internet SMTP server.
In this example, we are going to use Gmail, but you can use a similar configuration for any other SMTP server, although you might have to look at the manual if that server is using SSL instead of TLS (in the latter, the connection starts in cleartext, and then the STARTTLS command makes it switch to TLS). You should read the manual anyway.
Note that you might need to enable IMAP in Gmail settings (I know IMAP has nothing to do with that, but...)

First, login as root and install postfix on your system:

sudo -i
apt-get install postfix

Then add the following lines to /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
smtp_tls_security_level = may

This tells Postfix it needs to relay all outgoing emails to Gmail, using the mentioned host and port, and using TLS.

The authentication credentials must be entered into /etc/postfix/sasl_passwd :

[smtp.gmail.com]:587    theUser@theDomain.tld:ThePassword

(Re)build the hash table:

postmap hash:/etc/postfix/sasl_passwd

This should create the file /etc/postfix/sasl_passwd.db

Make sure these files have permissions such as read-write and are owned by root:

chmod 600 /etc/postfix/sasl_passwd*
chown root /etc/postfix/sasl_passwd*


Restart postfix:

sudo service postfix restart

Try to send an email:

apt-get install mailutils
mail -s "The Email Subject" an-address@on-the-internet.com

Type your email at this point. Press Ctrl-D when you are done. When it asks for "Cc:", press Enter.

Watch the system log file:

tail -f /var/log/syslog

In case it failed, do not try to send the email again with the mail command.
Postfix should have automatically deferred the message to send it later.

You can look at the queue with
postqueue -p

(command not found at this point? Try with sudo...)

You can flush the queue, which actually means trying to send the messages again, with
postqueue -f

If for some reason you want to delete all deferred messages in the queue:
postsuper -d ALL deferred

If your system complains about not being able to reach Gmail on an IPv6 address, run Postfix in IPv4-only mode by adding the following line to /etc/postfix/main.cf and restart Postfix:
inet_protocols = ipv4

I hope that helped.

No comments:

Post a Comment