Sending email via Gmail using PHP & Postfix

So I’ve started trying to teach myself PHP and MySQL.  I’ve built a CentOS 5.5 server and have installed a LAMP environment to play around with.  While stepping through the exercises and playing with the mail() function in PHP, I realized that my test messages weren’t being delivered.  A friend pointed out that I didn’t install the Sendmail package, which typically installs w/ CentOS, but he suggested I install Postfix instead as it’s easier to manage and not quite as temperamental as Sendmail.  After installing Postfix, the PHP script would work, but it took about 10-15 minutes to send the message and even then, it would get routed to my Gmail SPAM folder.  After a considerable amount of digging I finally fixed it.

I’ve attached a link below to the original article I referenced to fix my problem (originally written by Jeremy Bouse), but have also snipped/edited the specific steps I used, just in case the original article disappears in the future.

(snipped and modified)

The first step is to create the file containing your authentication credentials. For this I used /etc/postfix/sasl_passwd to which I added this line:

smtp.gmail.com:587    myusername@gmail.com:mygmailpassword

You’ll want to be sure this file is protected so I recommend root:root ownership and 0600 permissions be set on it. You’ll then want to run the following to create the hash mapped version as root.

postmap hash:/etc/postfix/sasl_passwd

Below is a copy of the lines I added to the bottom of my main.cf file:

/etc/postfix/main.cf

myhostname = localhost.localdomain
mydestination = localhost.localdomain
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_password
smtp_sasl_security_options =
smtp_tls_security_level = may
relayhost = smtp.gmail.com:587

After making these changes to the main.cf config file, I reloaded Postfix so it would pick up the changes, reran my PHP script containing the mail() function and it worked like a champ.

http://serverfault.com/questions/119278/configure-postfix-to-send-relay-emails-gmail-smtp-gmail-com-via-port-587

Leave a Reply

Your email address will not be published. Required fields are marked *