Configure Postfix to Use Gmail SMTP on Ubuntu

Update: This article is part of WordPress-Nginx tutorials series.

If you want to use a Gmail account as a free SMTP server on your Ubuntu-Linux server, you will find this article useful. This guide is tested with Ubuntu 12.04. If you face any issue, feel free to use comments-section below.

Relaying Postfix mails via smtp.gmail.com:

First, install all necessary packages:

sudo apt-get install postfix mailutils libsasl2-2 ca-certificates libsasl2-modules

If you do not have postfix installed before, postfix configuration wizard will ask you some questions. Just select your server as Internet Site and for FQDN use something like mail.example.com

Then open your postfix config file:

vim /etc/postfix/main.cf

and following lines to it:

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

You might have noticed that we haven’t specified our Gmail username and password in above lines. They will go into a different file. Open/Create

vim /etc/postfix/sasl_passwd

And add following line:

[smtp.gmail.com]:587    [email protected]:PASSWORD

If you want to use your Google App’s domain, please replace @gmail.com with your @domain.com

Fix permission and update postfix config to use sasl_passwd file:

sudo chmod 400 /etc/postfix/sasl_passwd
sudo postmap /etc/postfix/sasl_passwd

Next, validate certificates to avoid running into error. Just run following command:

cat /etc/ssl/certs/Thawte_Premium_Server_CA.pem | sudo tee -a /etc/postfix/cacert.pem

Note: If you run into issues with above command, try changing certificate name to thawte_Primary_Root_CA.pem in above command. Thanks Alexander Bakker for the note.

Finally, reload postfix config for changes to take effect:

sudo /etc/init.d/postfix reload

Testing

Check if mails are sent via Gmail SMTP server

If you have configured everything correctly, following command should generate a test mail from your server to your mailbox.

echo "Test mail from postfix" | mail -s "Test Postfix" [email protected]

To further verify, if mail sent from above command is actually sent via Gmail’s SMTP server, you can log into Gmail account [email protected] with PASSWORD and check “Sent Mail” folder in that Gmail account. By default, Gmail always keeps a copy of mail being sent through its web-interface as well as SMTP server. This logging is one strong reason that we often use Gmail when mail delivery is critical.

Once configured, all emails from your server will be sent via Gmail. This method will be useful if you have many sites on your server and want them all to send emails via Gmail’s SMTP server.

Alternatively, you can use a plugin like WP Mail SMTP so that mails from your particular WordPress site will be sent using Gmail’s SMTP server.

Please note that Gmail’s SMTP server has a limit of 500 emails per day. So use wisely! 🙂

Troubleshooting

Error: “SASL authentication failed; server smtp.gmail.com”

You need to unlock the captcha by visiting this page https://www.google.com/accounts/DisplayUnlockCaptcha

You can run test again after unlocking captcha.

P.S. Do not miss out on our other helpful tutorials. Join us on twitter and facebook for more updates.

 

161 responses to “Configure Postfix to Use Gmail SMTP on Ubuntu”

  1. A great big thank you to you this worked brilliantly on my Ubuntu 12.04.2 LTS install

  2. I felt the need to say thank you since you were a big help – straightforward explanation that worked after the first try 🙂

  3. Man ! I owe you big time 😀 thanks heaps , This is a lot simple and understandabale than any other thing I’ve found , It actually works ! KEEP UP THE GOOD WORK ! CHEERS !!!

  4. After configured everything and download the root cert from Thawte I am receiving the following error. Could you please help me?

    Action: failed
    Status: 5.7.0
    Remote-MTA: dns; smtp.gmail.com
    Diagnostic-Code: smtp; 530 5.7.0 Must issue a STARTTLS command first.
    f71sm25739776yha.8 – gsmtp

    • USE THIS in the main.cf

      eliminates default security options which are imcompatible with gmail

      smtp_sasl_security_options =

      • I also have this problem.

        I can’t spot the error.. Any suggestions?

        My main.cf looks like:

        myhostname = raspberrypi
        alias_maps = hash:/etc/aliases
        alias_database = hash:/etc/aliases
        myorigin = /etc/mailname
        mydestination = raspberrypi, localhost.localdomain, localhost
        relayhost = [smtp.gmail.com]:587
        mynetworks = 127.0.0.0/8
        mailbox_size_limit = 0
        recipient_delimiter = +
        inet_interfaces = all
        inet_protocols = ipv4

        smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
        biff = no

        # appending .domain is the MUA's job.
        append_dot_mydomain = no

        # Uncomment the next line to generate "delayed mail" warnings
        #delay_warning_time = 4h

        readme_directory = no

        # TLS parameters
        smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
        smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
        smtpd_use_tls=yes
        smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
        smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

        # use sasl when authenticating to foreign SMTP servers
        smtp_sasl_auth_enable = yes

        # path to password map file
        smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd

        # list of CAs to trust when verifying server certificate
        smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

        # eliminates default security options which are imcompatible with gmail
        smtp_sasl_security_options =

  5. Anyone else facing an ‘Authenication Required’ error message when sticking to the tutorial (although setting up the password file worked flawlessly)?

  6. XXXx@XXXXXX:/etc/postfix$ echo “Test mail from postfix” | mail -s “Test Postfix” [email protected]
    The program ‘mail’ is currently not installed. To run ‘mail’ please ask your administrator to install the package ‘mailutils’

  7. It is not the first tutorial that i tried, but it is the first that worked on my Ubuntu 12.04.
    It is excellent. Thank you very much

  8. Worked great! However, in my case I had to do one more thing which I thought I’d share here. After sending the test email, I got a “Suspicious sign-in prevented” email from google in my inbox. So, I went to google.com to search for a solution, saw a big red banner saying something like “someone tried to login to your email from a new application, was it you?” I clicked through several screens to say “yes, this was me”.

    echo “Test mail from postfix” | mail -s “Test Postfix” [email protected]

    …and this time got test email in gmail account!

    Just sharing this in case someone else gets this.

  9. When executing the following command:

    postfix/postfix-script: fatal: the Postfix mail system is not running
    [fail]

  10. sudo /etc/init.d/postfix reload
    * Reloading Postfix configuration… postfix/postfix-script: fatal: the Postfix mail system is not running
    [fail]

    • Just try… `sudo /etc/init.d/postfix restart`

      If you get error `bind 0.0.0.0 port 25: Address already in use` then it might be the case some other mail program is already present in your system.

  11. Hi,
    I configured postfix as above, but unfortunately send mail root through root@ not from gmail , and no email at send mail of gmail a/c, I double checked all config exactly as per this doc, Can you please help me , Is their any additional configuration I need set up?

    -Subin

    • If gmail is configured correctly, FROM address will be overridden with Gmail’s email address for all outgoing email.

      It looks like your emails aren’t sent by Gmail. Hence they are not appearing in Gmail’s sent mail folder as well.

      • Hi subin

        Did you get a resolution to your issue? I’m facing the same. The FROM address is not being overridden. So it is trying to send from “linuxuser”@gmail.com instead of “gmailname”@gmail.com

        • This is really strange as Gmail makes sure that we can not override FROM name on the go.

          In fact, that is one reason to NOT use Gmail in many production server where system need to send emails from multiple FROM addresses.

  12. I have a problem, everything worked without a problem , no errors no nothing, but when i check my gmail account nothing was sent? What do you think the problem might be?

      • Thanks for the promp response and sorry for the late comeback, but I found out that at the place where i was trying to set this up smtp is a no no, it has been disabled on the network for security reasons.

          • Not all outbound mail. 99% of the users use windows and have outlook configured through the company servers. I’m the oddball there because i’m trying to get a backup application running on a linux pc for some of the older computers that can’t be replaced for some reason or another, and when i say old i mean going on 20 years, they’re practicaly the legal drinking age. I was trying to configure email client on that. Thanks for all the help.

  13. after configuring postfix as above I cann’t receive any mail from the server to my mail id

  14. Hi Rahul, Its a great post, helpful for me, The issue I posted earlier is resolved, By default sendmail also installed and sending mail through sendmail, I removed sendmail, now everything is as expected. Thank you somuch

    -Subin

  15. I have strange problem please help me

    it was all working fine,

    now i cannot send email to gmail.com,yahoo.co.in,

    but i can send to hotmail and google hosted email service,rediffpro account.

    i cant understand what is this problem please help….

    • Look for postfix logs and also Gmail’s sent folder for email address being used.

      On other end, check spam folder on email accounts where you are not receiving mails.

  16. a Big thanks for the point shoot instructions. It worked pretty well. Now I will try to configure my other domain SMTP here (you showed it how 🙂 )….

  17. Just wanted to extend my thanks to you for this succinct write-up. I have setup mail on Ubuntu servers before, but this was my first time attempting SMTP via Postfix, and this was a very simple and quick mail setup that just works.

    Nicely done!

  18. Works Great!! thanks a lot for the well documented steps.

    Found “aptitude” command does’t work on Ubuntu 13.04 ( 13.04, Raring Ringtail ) ,
    – Used insted “apt-get ”

    sudo aptitude install postfix mailutils libsasl2-2 ca-certificates libsasl2-modules

    WORKS great!, Thank you.

  19. Why not switch to msmtp instead of postfix if you’re only going to use it for sending through gmail? I’ve not compared/tested but I think its memory footprint is much smaller… While setup is similar 🙂

  20. Hey man,
    You’re really the best… I’ve been on this for over a week but U did it in less than 30 minutes!!! Thanks a million. I hope I will be able to send with attachments too!!!
    Thany you so much… You deserve the best

  21. Beautiful! You’re a hero of modern times, my friend, what a superb tutorial. I shall now send emails from the command line alone, simply because I can 🙂

  22. Thank you.
    Unfortunately I get this:
    Nov 8 12:27:41 ODIN2 postfix/error[20109]: EDB1E77006EE: to=, orig_to=, relay=none, delay=0, delays=0/0/0/0, dsn=5.0.0, status=bounced ([smtp.gmail.com]:587)

    I have ssmtp on my server, but cron did not like to use it. I assume it’s not the cause of this problem.
    also: I use 2-factor auth, but I gave it an application-specific password. – and it does not seem to be an authentication problem.
    Please help me. 🙂

    • Also, I did not get a wizard, you mention that I should configure as “internet site”.
      I changed
      myhostname ODIN2.example.com

      now the error is still the same, except for the destination address being all wrong
      Nov 8 12:54:12 ODIN2 postfix/error[25061]: 871077700701: to=, relay=none, delay=0, delays=0/0/0/0, dsn=5.0.0, status=bounced (odin2.example.com)

      ow can I do this” select Internet Site and for FQDN use something like mail.example.com”

  23. Hi Rahul,

    This tutorial has been very helpful many times. However, I am stuck with a couple of clients using Zoho (at my recommendation as it is free-er)

    Do you have any experience setting up postfix with Zoho? If you do, would you be willing to write another lovely tutorial?
    The internet has failed me and I was not able to find anything but the following:
    https://forums.zoho.com/topic/setup-postfix

    Thanks for your time,
    Tamara

    • I never used Zoho mail. But if they are providing SMTP interface then you can just substitute values for Zoho SMTP in place of Gmail SMTP to get it working.

      All this tutorial does in relay outgoing emails via Gmail’s SMTP server rather than local sendmail program.

      • Thank you for the prompt response!

        Zoho uses an SSL connection rather than TLS. I’ve started playing with the config outlined at the following article http://major.io/2007/07/01/enable-ssl-support-in-postfix/, but got stuck on how to add the username and password.

        Would you know if I’d still be able to use the following for storing the username and pass

        smtp_sasl_auth_enable = yes
        smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
        smtp_sasl_security_options = no anonymous

        Thanks again 😀

        • Those settings comes into picture when “your postfix server” is used by other applications. In this case, you are using “zoho server” so I don’t think your postfix’s master conf will matter much.

          Try replacing [smtp.gmail.com]:587 with [smtp.zoho.com]:465 evrywhere in this article.

          • Replacing with [smtp.zoho.com]:465 in main.cf unfortunately doesn’t help, since Postfix doesn’t support legacy TLS. I happened to get Postfix work with Zoho email while setting up gitlab. Details are here. Details Link.

  24. After issuing command:
    sudo chmod 400 /etc/postfix/sasl_passwd

    Come with this issue:
    sudo: unable to resolve host mail

    Masters, need some help please. Thanks a lot.

  25. works like a freaking charm…… whoever did this tutorial he freaking rock….thanks wherever you are

  26. Thank you very much for this excellent tutorial. It works fine on Ubuntu 12.04 LTS but not on 13.10

    • We only use LTS releases for Ubuntu.

      However, if you manage to get this working on Ubuntu 13.10, feel free to suggest changes and I will have this post updated with your contribution.

  27. And how to debug if the testrun fails? As far as I can tell it doesn’t even say any error messages or warnings.

  28. Dear, excellent posting, followed step by step and working like a charm.
    All the best! Regards raja

  29. Dec 19 12:11:42 user-System-Product-Name postfix/smtp[20581]: B3DA31A421D2: SASL authentication failed; server smtp.gmail.com[74.125.143.109] said: 535-5.7.8 Username and Password not accepted. Learn more at?535 5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 y11sm1790904lbm.13 – gsmtp
    Dec 19 12:11:43 user-System-Product-Name postfix/smtp[20581]: B3DA31A421D2: SASL authentication failed; server smtp.gmail.com[74.125.143.108] said: 535-5.7.8 Username and Password not accepted. Learn more at?535 5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 mq10sm1794674lbb.12 – gsmtp
    Dec 19 12:11:43 user-System-Product-Name postfix/smtp[20581]: connect to smtp.gmail.com[2a00:1450:4008:c01::6d]:587: Network is unreachable
    Dec 19 12:11:43 user-System-Product-Name postfix/smtp[20581]: B3DA31A421D2: to=, relay=none, delay=2.2, delays=0.08/0/2.2/0, dsn=4.4.1, status=deferred (connect to smtp.gmail.com[2a00:1450:4008:c01::6d]:587: Network is unreachable)

  30. Worked on Ubuntu 12.04
    Thank you a lot! I spent like 4 days with sendmail, postfix, dns server set up. So fed up with all these tech challenges. Finally reinstall Ubunut and you post saved me!

  31. Hi, thanks for your guide. I got it to work for outgoing emails from root@localhost. What must i do to get it to work for incoming emails sent to gmail? I tried searching on the internet but came up with nothing :(. Hopefully you have a solution for me.

  32. sorry there is a typo above, i mean incoming emails sent to root. not gmail. thanks again!

    • Sorry I couldn’t understood your problem clearly. This article deals with outgoing mails only.

      Your server cannot receive incoming emails for root@localhost from outside world. Incoming mail is whole different topic.

      If you are concerned about “replies” to mails going through Gmail; those “replies” will be directly reach to Gmail server.

  33. Fantastic tutorial but I’m falling at the first hurdle;-
    Reading packages lists…Done
    Building dependency tree
    Reading state information… Done
    Package mailutils is not available, but is referred to by another package.
    This may mean that the package is missing, has been obsoleted, or is only available from another source
    E: Package ‘mailutils’ has no installation candidate
    E: Unable to locate package libsas12-2
    E: Unable to locate package libsas12-modules

  34. I did what you said but when i check Sentmail, the mail is not there…the resident also did not recieve any mail.pls help.i m using uunty 12.04 lts.Thank you.

  35. i m getting mail in mailbox but no mail in sent mail in my gmail account.my host name is my computer name without domain and i m not able to change it by editing /etc/hostname.

      • changed my host name by editing /etc/hostname and /etc/hosts but now host myfqdn is not working and giving 3(NXDomain) error.Still the mail is sent via my fqdn and not gmail.

      • Reverse Dns not working in my fqdn.its giving 3(NXDomain)error.i enabled smtp my gmail account whose details i saved in/etc/postfix/sasl_passwd so whenever i send to any other gmail account via command prom then its working but if i send it to username@myfqdn then its not sent via gmail accnt .i m not able to send any mail to my fqdn.for example if fqdn is myhost.mail.com then i can send mail to [email protected] but not to myhost.mail.com.when i try to send mail to myhost.mail.com then it gives failure report in my gmail account…if my hostname is myhost and fqdn is myhost.mail.com then sending mail to [email protected] is giving failure report but [email protected] is sending mail bt not via gmail.

        • I think you are having problem for sending to only one particular domains – your FQDN in this case.

          Check postfix value for mydestination setting. If its anything apart from localhost, or contains your FQDN, then remove that value from there.

    • Not sure what are you asking for? All mails will be through Gmail account’s email address. You can use an email address with Google Apps mail.

  36. Hello sir, thank you for your great tutorials, i know this is not the right place for this but unfortunely im a windows user with xampp server, i configured my php.ini and my sendmail.ini for gmail smtp, my php mail sender script says mail successfully sent, but i dont recive any thing, i tried all possible sollutions on internet but still got this problem! so maybe you cn helep me 🙁 PLEAZEEE!

  37. Thank you for this tutorial! I got my gmail smtp on postfix to work, Quick question which I really pray u have an answer for it! How do I configure fail2ban for postfix if I followed your tutorial? thank you!!!

    • How do I configure fail2ban for postfix if I followed your tutorial?

      The same way you would have configured when not using Gmail as reply in postfix. I guess fail2ban comes into picture if you are running a public SMTP server. In this case, it is assumed that postfix is not accessible to the outside world via SMTP.

      Gmail accounts has very low sending limits. So we use this kind of setup only in small apps for notification email types only.

    • Looks like pool.ftc-c.com is your hostname and mails are sent from postfix only. Are you sure you have configured Gmail setup properly?

      Because all mails replayed from Gmail uses Gmail’s email address as FROM address.

  38. Hi, I follow your instruction to send mail via gmail using postfix. However, my network is working behind proxy with userid and password. Will you help me setting up these parameters so that I also feel happy to send mail using this way.

  39. Thank you very much, this tutorial was spot on, and very easy to follow. And as an added bonus it worked like a peach! You Rock, Rahul, thanks.

  40. when I am at work where we have a domain it works fine, when I am at home it complains about fqdn and won’t send, what can I do to make it work at home where I don’t have a domain?

    • Postfix via Gmail shouldn’t care about domain or IP. This is used mostly in locations where server/machine IP is dynamic.

      I am assuming that you have a postfix+gmail setup on your laptop which is you are using at home/work.

      When at work try ping yourdomain.name. Repeat same commands at home. If there is a difference in IP, try to offset that difference by modifying local /etc/hosts.

      Another case, is postfix+gmail setup is present at work machine but postfix has smtpd_recipient_restrictions enabled with setting reject_non_fqdn_sender. Remove reject_non_fqdn_sender so your (senders) IP/FQDN will not be verified.

      References: http://www.postfix.org/postconf.5.html#smtpd_sender_restrictions and http://www.akadia.com/services/postfix_uce.html

  41. Thanks for the Plugin suggestion, I couldn’t make relay setup working being in hurry but the Plugin WP Mail SMTP works great for me.

    • Where did you get stuck? WP Mail SMTP plugin might slow down few WordPress feature as SMTP connections are generally blocking in nature.

      Using relay host is useful as postfix uses mail queue.

  42. This is a great tutorial! Followed step by step and was able to get it working. Had some issue with sendmail already running on port 25, but I removed it and rebooted and now it works like a champ!

  43. Every time i boot my server, I get that test mail… x2 and every now and again while its up… how to fix. thanks

    • This is not related to this article. This article doesn’t have test mail sending on boot.

      Anyway, check crontab. It looks like cronjob.

  44. hi. really nice tutorial. i got it working simply by following this tutorial.
    when i send emails, the recipient sees root (as name, the email address appears correctly).
    it appears as root is there a way to change the root to another name.
    when i send from my thunderbird using this email address it appears the name i have setup.

  45. I get the following log message from gmail: “….The IP you’re using to send mail is not authorized to 550-5.7.1 send email directly to our servers. Please use the SMTP relay at your 550-5.7.1 service provider instead…. ”
    Could you suggest a workaround?

  46. Thanks @Rahul,
    I have one issue though, if you could help.

    I have installed it as you explained it here step by step for my WordPress site. I use Contact Form7 plugin for creating my forms. So I am able to send emails, but the Sender address in all those emails is what I have entered in sasl_passwd file. And it ignores the Sendaddress in the ContactFrom7 plugin. Is there a solution for this ?

  47. Rahul: It didn’t work perfectly initially. But commenter’s followup questions echoed my issues. The machine said “bind 0.0.0.0 port 25: Address already in use. ” You suggested that this might be due to “some other mail program is already present in your system.” I did “apt-get –purge remive sendmail” to get rid of my best guess, but apparently sendmail it had its claws sunk deep into the OS: I continued to get errors when I did your example test.

    But one reboot and Hey Presto! it sends mail!

    Many thanks, Rahul! It works good. Thank you for writing up this very handy how-to.

    One wonders how you figured it out?