How to replace Sendmail with Gmail smtp on Ubuntu server

Today my goal was to be able to send mails from PHP from my web-server using Gmail smtp.

  1. My server runs on Apache with vhosts: I need a separate mailbox for every domain.
  2. I don’ want to manage a MTA because it’s resource and time expensive, so I want to send mails trough a Gmail account.
  3. I want the system to be fast and easy to maintain.

The standard packages such as postfix, sendmail, qmail etc doesn’t meet the last two requirements, so I had to choose an alternative to postfix: MSMTP

Open a Gmail account

My suggestion is to not use your personal Gmail account, so probably will be a good idea to open a brand new one dedicated to the server.

Install MSMTP

That’s an easy task: use apt-get to achieve it.

sudo apt-get install msmtp ca-certificates

With this command we have installed also some authority certificates useful to verify SSL connection.

Configure MSMTP

The default config files for MSMTP are located in SYSCONFDIR/msmtprc and ~/.msmtprc.
Neither the first or the second was created by apt, so I preferred to have a folder in /etc where store more than one config file if needed.
Same for the logs.

sudo mkdir /etc/msmtp
sudo mkdir /var/log/msmtp

Then I’ve created the config file: citex0 is the name of my server, change it.

sudo touch /etc/msmtp/citex0
sudo nano /etc/msmtp/citex0

this is what’s inside: remeber to change your mailbox and password

# Define here some setting that can be useful for every account
defaults
        logfile /var/log/msmtp/general.log

# Settings for citex0 account
account citex0
        protocol smtp
        host smtp.gmail.com
        tls on
        tls_trust_file /usr/share/ca-certificates/mozilla/Equifax_Secure_CA.crt
        port 587
        auth login
        user [email protected]
        password my_server_password
        from [email protected]
        logfile /var/log/msmtp/citex0.log

# If you don't use any "-a" parameter in your command line,
# the default account "citex0" will be used.
account default: citex0

Test MSMTP

change the [email protected] with your own recipient, the file path if needed and run:

echo -e "Subject: Test Mail\r\n\r\nThis is a test mail" | msmtp --debug --from=default -t [email protected] --file=/etc/msmtp/citex0

Troubleshooting MSMTP

Probably the first time you’ll try to send a mail to Google’s smtp from a server’s ip, BigG will deactivate your account.
This is the result on the log or command line output:

<-- 535-5.7.1 Please log in with your web browser and then try again. Learn more at
<-- 535 5.7.1 https://support.google.com/mail/bin/answer.py?answer=78754 b49sm36363995eem.16
msmtp: authentication failed (method LOGIN)
msmtp: server message: 535-5.7.1 Please log in with your web browser and then try again. Learn more at
msmtp: server message: 535 5.7.1 https://support.google.com/mail/bin/answer.py?answer=78754 b49sm36363995eem.16
msmtp: could not send mail (account default from /etc/msmtp/citex0)

To avoid this you only need to verify your Google Account by inserting your phone.
Simply try to login with your server account and you'll be prompted for your phone number.
Insert the right one and they will send you a code to unlock your server account.

This is what happens when everything is alright!

<-- 235 2.7.0 Accepted
--> MAIL FROM:
<-- 250 2.1.0 OK e2sm36547326eeo.8
--> RCPT TO:
<-- 250 2.1.5 OK e2sm36547326eeo.8
--> DATA
<-- 354  Go ahead e2sm36547326eeo.8
--> Subject: Test Mail
-->
--> This is a test mail
--> .
<-- 250 2.0.0 OK 1355059058 e2sm36547326eeo.8
--> QUIT
<-- 221 2.0.0 closing connection e2sm36547326eeo.8

Anand Rai told me there is a way to do it without entering a captcha or password using web browser.

I suggest to not use this on production server for the security implications coming from enabling the "less secure apps". BTW thanks Anand!

Configuring Apache\PHP to use MSMTP

To force PHP to use MSMTP when called by Apache you have to set the environment variable sendmail_path.

php_admin_value sendmail_path "/usr/bin/msmtp --debug --from=citex0 --file=/etc/msmtp/citex0 -t"

At this point I had to fix some permission and owners

sudo chmod 600 /etc/msmtp/citex0 
sudo chown -R www-data:www-data /var/log/msmtp 
sudo chown -R www-data:www-data /etc/msmtp/

Reference

The official documentation of the project: http://msmtp.sourceforge.net/documentation.html

  • nunuux

    Only one thing to say : Thanks a lot, your post has saved my life ๐Ÿ˜‰

  • Great article – I have a small problem, when I try and run the test I get..

    — ignoring system configuration file /etc/msmtprc: No such file or directory
    — msmtp: /etc/msmtp/gwilym: must be owned by you

    I’m pretty sure /etc/msmtp/gwilym is owned by me as I used sudo to create it and when I run ls -l it says gwilym is the owner.

    Any advice appreciated…

    • I miss the system configuration too, this is ok.

      a couple of tests:

      – does the test command work with sudo or runned by root?
      – can you post the complete output of ls -l /etc/msmtp/gwilym (is the group ok?)
      – is the /etc/msmtp/ directory accessible by your user (typically 755 or +x)
      – can you read the file? ex. cat /etc/msmtp/gwilym
      – try to copy the config file in your home and change the command accordly

      echo -e “Subject: Test MailrnrnThis is a test mail” | msmtp –debug –from=default -t [email protected] –file=/home/gwilym/msmtp.conf

      • Hiya – thanks for replying ๐Ÿ™‚

        Output of ls -l /etc/msmtp/gwilym :: -rw-r–r– 1 root root 611 Oct 1 09:51 gwilym

        I get the same error when running the test as sudo, I can edit the file ‘gwilym’ from my user no problem and changing to 755 makes no difference.

        Regards copying the config file do you mean copy /etc/msmtp/gwilym to home?

        • My output of ls:

          # ls -l /etc/msmtp/citex0
          -rw——- 1 www-data www-data 1052 Sep 13 23:27 /etc/msmtp/citex0

          Your ls says that root is the owner of that file.

          sudo chown gwilym:gwilym /etc/msmtp/gwilym

          will solve your issue.

          • Thanks Emanuele – working! Really appreciated … I might email you about some work helping setup a VPS… if you do that sort of thing…

          • I can’t promise to solve every issue, but I can try ๐Ÿ™‚

          • sticksnstonesnz

            Another trick for the uneducated (me) – mail sent using this method is likely to end up in the spam folder, so if it isn’t getting through check there first ๐Ÿ™‚

          • It never happened to me. Big G blocked my server account a couple of times for suspicious activity… but this was solved by entering and confirming the phone number…

            If you use this config to make a public contact form (or similar) work, be sure to integrate some kind of spam checktrap.

            Also check that the mails your system is sending have the object field and some text in it.

            Then be sure that you did ever marked a mail from your system as spam, otherwise gmail will remember your choice.

            You can also search in the mail headers for more useful info… Maybe you’ll find who marked that mail by spam.

            If you run the test command does the mail end up the spam?

          • sticksnstonesnz

            Hi again – where do you apply – php_admin_value sendmail_path “/usr/bin/msmtp –debug –from=citex0 –file=/etc/msmtp/citex0 -t” – is that in the php.ini file?

          • yes it is, and also be sure to set it in the file considered by apache.

            Typically on Ubuntu
            /etc/php5/apache2/php.ini

  • Matthew Browne

    Very helpful, but had to make a few changes to get it to work. I had to change the tls_trust_file setting to /etc/pki/tls/certs/ca-bundle.crt (note: I’m running CentOS 6). Also, the sendmail_path
    PHP setting recommended in the link didn’t work for me; I had to change
    it to “/usr/bin/msmtp -C /etc/msmtp/eventjournal -t” (and restart
    Apache since I changed this in php.ini rather than in an .htaccess
    file).

    • Good to know! Thank you.

      Unfortunately the last Red Hat based distro I’ve used was RH5 ๐Ÿ˜› so I’m not so up-to-date with this.

      Anyway I think that the setting for tls_trust_file is only an issue of file path that change on different dristo.

      The second one, according to msmtp –help, should be the same: “-C, –file=filename Set configuration file.”…. so this is weird…

      • Matthew Browne

        Maybe it didn’t like the “debug” or “from” option…in any case it’s working now ๐Ÿ™‚

        • Well, this is the most important thing ๐Ÿ˜€

          Again, thanks for sharing this info

    • guebre

      Hello everyone. I came to you to seek your help. I want to set msmtp with php for alerts ntopng which is a network probe. my system is centos 7. I have trouble for that. can you help me please? I am just a beginner in Linux. thank you in advance!!!

    • Matthew Browne

      Also, when testing, be sure to specify a “From” address, otherwise some destinations including Gmail might reject the message.

  • guebre

    Hello everyone. I came to you to seek your help. I want to set msmtp with php for alerts ntopng which is a network probe. my system is centos 7. I have trouble for that. can you help me please? I am just a beginner in Linux. thank you in advance!!!