Tutorial

How To Use Gmail or Yahoo with PHP mail() Function

Published on August 3, 2013
How To Use Gmail or Yahoo with PHP mail() Function

What the Red Means

The lines that the user needs to enter or customize will be in red in this tutorial!

The rest should mostly be copy-and-pastable.

About PHP mail()

The PHP mail() function uses the program in sendmail_path configuration directive to send emails. This is set up as sendmail by default.

While most Linux installations have sendmail preinstalled, there is always a hassle of setting up SPF/PTR records, generating DKIM keys and a lot more to ensure that the email sent by your PHP script is not flagged as spam. A SMTP client called MSMTP can be used to send emails using third-party SMTP servers, this can also be used by PHP's mail() in the place of sendmail.

Installation

To install MSMTP on Fedora Linux use yum:

yum install msmtp

CentOS repository doesn't have a RPM package for MSMTP so we need to install it from source:

yum install make gcc pkgconfig
wget http://sourceforge.net/projects/msmtp/files/msmtp/1.4.31/msmtp-1.4.31.tar.bz2/download
tar -xvf msmtp-1.4.31.tar.bz2
cd msmtp-1.4.31
./configure
make
make install

The latest version is 1.4.31 at the time of this writing but it may change in future so to get the latest version, visit this sourceforge page.

On Ubuntu/Debian distribution use apt-get:

apt-get install msmtp

Arch Linux users:

sudo pacman -S msmtp

Configuring MSMTP

The configuration file of MSMTP is stored in ~/.msmtprc for each user and /etc/msmtprc is the system wide configuration file. Open the configuration file in your directory.

vi ~/.msmtprc

Add the following lines for a Yahoo account:

account yahoo
tls on
tls_starttls off
tls_certcheck off
auth on
host smtp.mail.yahoo.com
user user1
from user1@yahoo.com
password yourYahooPa5sw0rd

For Gmail, use the following settings:

account gmail
tls on
tls_certcheck off
auth on
host smtp.gmail.com
port 587
user user1@gmail.com
from user1@gmail.com
password yourgmailPassw0rd

This file can also have more than one account, just ensure that the "account" value is unique for each section. Save the file and use chmod to make this file readable only by the owner since it contains passwords. This step is mandatory because msmtp won't run if the permissions are more than 600.

chmod 600 ~/.msmtprc

Before implementing this in PHP, check from the command-line to ensure it works properly. To do this, create a plain text file containing a simple email:

echo -e "From: alice@example.com \n\
To: bob@domain.com \n\
Subject: Hello World \n\
\n\
This email was sent using MSMTP via Gmail/Yahoo." >> sample_email.txt

Now send this email:

cat sample_email.txt | msmtp --debug -a gmail bob@domain.com

Replace the word "gmail" with "yahoo" or whatever you entered for the "account" option. You'll see a lot of messages because of the "--debug" parameter. This is to make troubleshooting easy if things don't work as expected. If bob@domain.com receives this email, everything is setup correctly so copy this file to the /etc directory:

cp -p ~/.msmtprc /etc/.msmtp_php

Change the ownership to the username under which the web server is running. This can be "apache", "www-data", or "nobody" depending on the Linux distribution on your VPS and web server installed:

chown www-data:www-data /etc/.msmtp_php

Configuring PHP

Open the php.ini file, its location varies according to the OS and PHP type installed (PHP CGI, mod_php, PHP-FPM etc):

vi /etc/php5/php.ini

Find the following line:

sendmail_path =

Modify it by adding the path to the msmtp command:

sendmail_path = "/usr/bin/msmtp -C /etc/.msmtp_php --logfile /var/log/msmtp.log -a gmail -t"

Manually create a log file and change its ownership to the username your web server is running as:

touch /var/log/msmtp.log
chown www-data:www-data /var/log/msmtp.log

Restart your web server to apply the changes:

service httpd restart

In Arch Linux, this is done using the systemctl command:

systemctl restart httpd

Depending on your OS and web server, replace "httpd" with the appropriate name. If PHP is running as a separate process (like PHP-FPM), restart it instead:

service php5-fpm restart

Create a PHP script with a simple mail() to test this setup:

<?php
if(mail("receipient@domain.com","A Subject Here","Hi there,\nThis email was sent using PHP's mail function."))
print "Email successfully sent";
else
print "An error occured";
?>

Access this file from the web browser.

http://www.example.com/file.php

If this email wasn't sent you can check the msmtp log file for errors.

tail /var/log/msmtp.log

Common errors

If the email was not sent when using the PHP script, troubleshoot as follows:

  • Check if you edited the correct php.ini file. This can be confirmed by creating a phpinfo(); file and checking the "Loaded Configuration File" section.
  • The path to the msmtp configuration file might be wrong or the web server doesn't have permission to read this file.
  • Check if an email is sent by running the script using command-line PHP:
    php /var/www/html/file.php

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
64 Comments
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Hi,

Thanks for the tutorial, it’s very clear and easy to follow. I have a problem though, and I’ve exhausted every method I can think of to solve it.

When using the sample PHP script above to send the message (through gmail), I get the following error:

errormsg=‘authentication failed (method PLAIN)’ exitcode=EX_NOPERM

I have followed the config settings to the letter, checked the php.ini path, etc. but to no avail. Any suggestions on where to start looking to solve this?

By the way, I can tell than an attempt to send the message through gmail was made because I received a message from Google about an unauthorized attempt to send email through my account. I double checked the password, file settings, file location, but all seems correct.

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
September 15, 2013

@wizardware: Google prevented the login so php was unable to send the message. Try to see if you can whitelist your app from your gmail account’s settings.

Bingo! That did the trick, problem solved. Thank you Kamal, I doubt I would have ever thought of this.

It looks like msmtp expects to see the system wide config file in /etc/msmtprc in spite of what you put in the sendmail path. You also need to change the SMTP port to 587 to work with gmail - at least for my paid Google Apps account.

Ignore my comment - i’d missed out the chown. After some sleuthing, I found the reason!

CentOS 6.4 x32 does not send e-mail in error: “msmtp: support for TLS is not compilled in”. How to fix the problem?

I had the same problem on CentOS 7 with msmtp version 1.6.2 this is how I solved it: In the directory where the source code of msmtp is located run these commands

make uninstall make clean yum install -y openssl* ./configure --with-tls=openssl make make install

That’s all =)

This method is not safe to use on shared environments, since the gmail/yahoo password is exposed and readable by any apache user.

@dmmd Add “tls_certcheck off” to the msmtp configuration file.

Hi there, great guide! It’s helped a lot, but I seem to be having issues getting the actual PHP to work.

Using command line msmtp command seems to work correctly, however using the PHP file sends back the failiure message. Just running “php mail.php” sends a “Authentication Failed (xxx Too Many Login Attempts)” which really confuses me. How could the command line email pass authentication but not the php file?

Thanks!

@em.apparition That error is displayed by the SMTP server (usually Gmail’s SMTP) if you’re using Google Apps without a DKIM record.

Read this http://serverfault.com/questions/543007/google-smtp-error-454-4-7-0-too-many-login-attempts-please-try-again-later

As to why it succeeds with the msmtp command I’m guessing that you’re using different email accounts in the ~/.msmtprc file and the one in /etc

something missing that make me crazy

yum install openssl yum install openssl-devel

and check send mail path

msmtp --version

I couldn’t send it from file.php but it worked on php /var/www/html/file.php What did I do wrong?

did you solve it?

I made it work. But not on 465 port. Actually I’m on 587… but would be more secure to use 465? I tried to exchange from 587 to 465 but with no success. I tried add ssl:// on smtp.gmail.com and no email wass ent

I cant get it working… Tryed postfix, sendmail, exim and now this, none work. Unnistalled everything before testing and followed the many tutorials. Using unbutu 12.4

On this one im having problem on step cat sample_email.txt | msmtp --debug -a gmail bob@domain.com

msmtp: cannot connect to smtp.gmail.com, port 587: Network is unreachable msmtp: could not send mail (account gmail from /home/username/.msmtprc)

This is the first time I’m doing stuff like this, so I almost don’t have any idea. My msmtprc file looks like this:

account killaribyte host mail.killaribyte.com port 587 from contacto@killaribyte.com user contacto password **********

When I run the command: dig MX killaribyte.com +short @ns1.digitalocean.com I got: 50 mail.killaribyte.com.

When I run: host mail.killaribyte.com ns1.digitalocean.com I got: Using domain server: Name: ns1.digitalocean.com Address: 198.199.120.125#53 Aliases:

mail.killaribyte.com has address ... (my IP)

And finally when I want to test it with: cat sample_email.txt | msmtp --debug -a killaribyte contacto@killaribyte.com I got: msmtp: cannot connect to mail.killaribyte.com, port 587: Connection refused msmtp: could not send mail (account killaribyte from /etc/msmtprc)

@lfna23 Try changing the port to 25

@luanpersini I think iptables is configured incorrectly to block outgoing connections or to prevent TCP connections. Try clearing the rules

<pre>iptables -X iptables -F</pre>

The command line of sending e mail works for me but when it comes to using the file.php, I encountered the error msg in the browser "Failed to connect to ssl://foeapp.com:465 [SMTP: Failed to connect socket: Connection refused (code: -1, response: )]”

Any idea? I thought i have changed it to 587 on the msmtp file.

I got it work. Used the wrong file.php. Apologies

Thank you for this tutorial! It was very helpful and did exactly what I needed!

Hi, followed and successfully configured.

However, its rather slow even for the test mail. Takes 3-5 mins, is it normal?

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
July 1, 2014

@erwin: What’s the latency between your server and the SMTP server you’re connecting to?

ping -c 4 smtp.mail.yahoo.com

or

ping -c 4 smtp.gmail.com

Ok … managed to nail the problem, droplet is in Singapore 1 with IPv6 enabled. It takes 3-5 minutes with IPv6 and after disabling IPv6 within OS (nothing else changed), it takes 2-4 seconds with IPv4.

I do not know if it is Google or DigitalOcean but I really hope that DigitalOcean will look into and check if there is a IPv6 routing or speed issue.

msmtp: TLS handshake failed: An unexpected TLS packet was received. msmtp: could not send mail (account gmail from /home/pi/.msmtprc)

I have no idea what this means, could someone help? I would greatly appreciate it!

When I run the test php command it throws this error.

sh: 1: /usr/sbin/sendmail: not found

Why is it even setting it to sendmail path? how can I change it to make it use the msmtp? Also it’s not logging this error. I had to run the php in putty to get this error msg =\

Please help

If you run php scripts from the command line the following configuration file is used:

/etc/php5/cli/php.ini

So you have to make those changes here.

Thanks jesin. I did the change to the apache2 php.ini so thanks for pointing out that its in the cli folder. Ok it sent the email successfully through putty but when trying to run it through the browser it gives an error. Problem if I go to the log now it just shows the one that got sent.

UPDATE It’s loggin under Apache2 though: msmtp: /etc/.msmtp_php: Permission denied

I have allowed myself to change it but now it gives this msg.

msmtp: /etc/.msmtp_php: must be owned by you

You’re welcome!

It must be owned by the user under which the Apache/php5-fpm process is running.

This could be www-data or apache2. Try changing the file’s ownership to one of them and also chmod this file to 600.

This comment has been deleted

    www-data worked! Thank you!

    One last question.

    How can I make it work with my process.php for my contact form? It’s using phpMailer.

    Example masked. Appreciate your help.

    <?
    
    
    $body = ob_get_contents();
    
    
    
    $to = 'someone@domain.com';
    $email = $email;
    $fromaddress = "me@domain.com";
    $fromname = "Online Contact";
    
    require 'library/PHPMailerAutoload.php';
    
    $mail = new PHPMailer();
    
    $mail->From     = "me@domain.com";
    $mail->FromName = "me@domain.com";
    
    $mail->AddBCC("me@domain.com");
    
    $mail->AddAddress($email,$name);
    
    $mail->WordWrap = 50;
    $mail->IsHTML(true);
    
    $mail->Subject  =  "domain.com (Contact Form)";
    $mail->Body     =  $body;
    $mail->AltBody	=  "Thank you for contacting us"; 
    
    
    if(!$mail->Send()) {
    	$recipient = 'me@domain.com';
    	$subject = 'Contact form failed';
    	$content = $body;
    	
    	
      mail($recipient, $subject, $content, "From: me@domain.com\r\nReply-To: $email\r\nX-Mailer: DT_formmail");
      exit;
    
    
    }
    ?>
    
    

    PHPMailer can be used to directly send emails via SMTP. Add these before $mail->Send():

    $mail->SMTPAuth   = true;                  // enable SMTP authentication
    $mail->SMTPSecure = "tls";                 // sets the prefix to the servier
    $mail->Host       = "smtp.example.com";      // the SMTP server
    $mail->Port       = 587;                   //the SMTP port for the server
    $mail->Username   = "yourusername@example.com";  // username
    $mail->Password   = "yourpassword";            // password
    

    They were there already and tried to send with it and didn’t work so I removed them assuming it will use the settings in the msmtp but still, didn’t work. =\

    Enable debugging with the following code:

    $mail->SMTPDebug  = 4;
    

    See what you get without the SMTP settings and with them.

    I’m having the same issue as dmmd running CentOS… Everything works up until I try to send the test email.

    [root@first msmtp-1.4.32]# cat sample_email.txt | msmtp --debug -a yahoo bob@domain.com ignoring system configuration file /usr/local/etc/msmtprc: No such file or directory loaded user configuration file /root/.msmtprc using account yahoo from /root/.msmtprc host = smtp.mail.yahoo.com port = 465 timeout = off protocol = smtp domain = localhost auth = choose user = myUserName password = * passwordeval = (not set) ntlmdomain = (not set) tls = on tls_starttls = off tls_trust_file = (not set) tls_crl_file = (not set) tls_fingerprint = (not set) tls_key_file = (not set) tls_cert_file = (not set) tls_certcheck = off tls_force_sslv3 = off tls_min_dh_prime_bits = (not set) tls_priorities = (not set) auto_from = off maildomain = (not set) from = myUserName@yahoo.com dsn_notify = (not set) dsn_return = (not set) keepbcc = off logfile = (not set) syslog = (not set) aliases = (not set) reading recipients from the command line msmtp: support for TLS is not compiled in

    Any suggestions? I already had the tls_certcheck set to off.

    Thanks.

    I guess you need to install OpenSSL and then reinstall MSMTP.

    yum remove msmtp
    yum install openssl
    yum install msmtp
    

    Thank you for this. Skipped sendmail for this. However I would suggest not disabling TLS cert check.

    Run this command to find cert issuer of your SMTP host.

    Then simply locate appropriate cert to be used by msmtp.

    tls_trust_file /usr/share/ca-certificates/mozilla/Thawte_Premium_Server_CA.crt
    domain yourdomain.com
    port 587
    keepbcc on
    

    Now I just need to figure out how to use passwordeval + gpg with this so password is not plaintext.

    It works for me exactly as described. I’m using an Archlinux and msmtp in version 1.4.32.

    Thanks, it’s very useful.

    I get to the part to enter my data into vi ~/.msmtprc however I cannot figure out how to save it and move to the next screen. Im a total noob with the terminal. Please help someone :)

    nevermind I figured this one out

    i am getting “The program ‘php’ is currently not installed. You can install it by typing: apt-get install php5-cli”

    I have the current LEMP stack installed

    That is exactly what you have to do:

    apt-get install php5-cli -y
    

    When I run php /var/www/html/file.php I get this in the terminal"Could not open input file: /var/www/html/file.php". The email sends if I send it from the terminal but no through the mail script, I also get a 404 error when I try to view the file.php in the browser

    HI, i’m having a problem with this. It was going ok until I tested in the browser and it did’nt send a email, now i’m getting this message back /usr/bin/msmtp: invalid option – ‘c’ when I run php /var/www/html/mailtest.php on the command line, Any ideas how I can sort this…

    Kamal Nasser
    DigitalOcean Employee
    DigitalOcean Employee badge
    November 23, 2014

    @Razor303: Make sure that the C is in uppercase:

    sendmail_path = "/usr/bin/msmtp -C /etc/.msmtp_php ...
    

    not

    sendmail_path = "/usr/bin/msmtp -c /etc/.msmtp_php ...
    

    Don’t forget to restart Apache or php5-fpm after updating php.ini.

    @jeff781158 If you see a 404 error on the browser the wrong file is being edited. Are you using Apache or Nginx?

    @kamain7 thanks dude, I can’t believe I missed that. anyway it’s worked with php from the command line I’m ssh in to my server from my phone when I get home I’ll test it properly, but it’s looking good

    @jeff781158 i’m using Apache2 at the min ! but i will be using Nginx when I move from testing, tinkering & developing to production. I’m not getting a 404 error, it sends it ok with php on the command line but not from the browser, php echo’s An error occured from the sample script. I haven’t got a domain name yet because i’m testing that wouldn’t matter, would it? below is the php script i’m using

    <?php if(mail(“myemail@gmail.com”,“Test messsage”,“Hi there Sh*t it worked !,\nThis email was sent using PHP’s mail function.”)) print “Email successfully sent”; else print “An error occured”; ?>

    I have saved the file as index.php in /var/www/html then in my browser I put servers-ip/index.php

    Kamal Nasser
    DigitalOcean Employee
    DigitalOcean Employee badge
    November 24, 2014

    @Razor303: What OS are you running? You might need to edit a different php.ini file depending on where the distribution’s packages store the configuration files by default. Are there any errors in /var/log/mail.err?

    @kamaln7 i’m using Ubuntu LAMP on 14.04. had a look in mail log there are a few entries because i’ve been sending a lot of test email some end with EX__OK they must be from the php command line because I can send mail from there, there are also some ending with --Header:

    EXAMPLE BELOW:

    [23-Nov-2014 23:37:08 America/New_York] mail() on [/var/www/html/index.php:2]: To: Myemail@gmail.com – Headers:

    @Razor303 Must be a problem with the permissions. Check who owns the config file:

    ls -l /etc/.msmtp_php
    

    Also check MSMTP’s config file for errors:

    tail /var/log/msmtp.log
    

    Hi, @jeff781158 this is what I get back when I check who owns the config file

    -rw------- 1 www-data www-data 155 Nov 22 18:04 /etc/.msmtp_php

    I can’t see any errors on the log file ???

    @Razor303 Just to confirm that the right php.ini file was edited, create a phpinfo file and access it on your browser. Check for the value of sendmail_path, if it shows the default value check for the php.ini file location in Loaded Configuration File and edit this file.

    This is a great article. I’ve used replacement modules for PHP mail before, and I’ve configured SMTP servers before… but I like this no-nonsense approach.

    Email sent this way is more reliable/deliverable because other mail servers will see the traffic coming from a well-known SMTP service like Google (instead of directly off my webhosting IP, which some sites will spam score or at least treat with skepticism).

    Hmm, odd problem occurring. I have only created an /etc/msmtprc file for config testing, not created a ~/.msmtprc. In this I have

    account gmailsam
    tls on
    tls_certcheck off
    auth on
    host smtp.gmail.com
    port 587
    from sam.richardson@mydomain.com
    user sam.richardson@mydomain.com
    password foobar
    

    Then I send this text message:

    From: sam.richardson@mydomain.com
    To: ronny@otherdomain.co.uk
    Subject: Test from our server
    
    This email from the our server, sam account
    

    When I test with debug, it authorises great thru google apps, but I get this:

    <-- 250 SMTPUTF8
    --> AUTH PLAIN AHNhbS5yaWNoYXJkc29uQHZvb2Rvb3Ntcy5jb20AYnJpZ2h0MG46
    <-- 235 2.7.0 Accepted
    --> MAIL FROM:<sam.richardson@mydomain.com>
    --> RCPT TO:<sam@mydomain.com>
    --> DATA
    <-- 250 2.1.0 OK ud4sm18672618wib.0 - gsmtp
    <-- 250 2.1.5 OK ud4sm18672618wib.0 - gsmtp
    <-- 354  Go ahead ud4sm18672618wib.0 - gsmtp
    --> From: sam.richardson@mydomain.com
    --> To: ronny@otherdomain.co.uk
    --> Subject: Test from our server
    -->
    --> This email from the our server, sam account
    -->
    --> .
    <-- 250 2.0.0 OK 1422374255 ud4sm18672618wib.0 - gsmtp
    --> QUIT
    

    Question: Where is it getting **RCPT TO: ** value from - there is no sam@ anywhere in this config.

    David

    Hi David,

    Please provide the entire msmtp command along with its arguments.

    Aaaaah. My bad, sorry. You are exactly right: I was specifying wrong recipient in msmtp command line, and expecting To: part to override, without specifying --read-recipient option.

    Thanks Jesin.

    Great tutorial - thanks!

    Only works by the terminal.

    What do I do?

    Are you using mod_php with Apache or PHP-FPM?

    Based on that you may have to edit /etc/php5/fpm/php.ini or /etc/php5/apache2/php.ini and modify sendmail_path.

    Thanks for this tutorial! Works great!!!

    Took a fair amount of time and hair pulling between figuring out exactly what parameters I needed to change, and remembering to uncomment the darn sendmail path >.<, but got everything working eventually!

    Everyone getting blocked by google may try this solution

    if you don’t have w3m text browser - install it with this command: sudo apt-get install w3m

    w3m https://www.google.com/accounts/DisplayUnlockCaptcha

    authorize with the e-mail you are using on the server confirm

    press q to quit w3m

    Great tutorial! But I’m running on a small problem that I don’t quite understand.

    I’ve installed msmtp, and configured everything of my Google account (Google apps account) above, (email and password are correct).

    Created the small email test php script. restarted apache2 and php5-fpm services (even my droplet after several attempts). But my email has never arrived.

    Strange this is. When I execute the test script via command line I get the my success message and when I go to the same test script via the browser (script is located in www directory), I get the error message, msmtp.log file is for some reason empty, maybe permissions problem?

    Oh yes: cat sample_email.txt | msmtp --debug -a gmail “myemail@myemail.com” works…

    Any help is welcome :)

    Never mind, forgot the part where I had to copy the .msmtprc file to the /etc directory d’oh!

    Hi,

    thank you for your great tutorial. I followed your tutorial and manage to send email when executing the php command line but not when I access the file from the web browser, what does this mean?

    I don’t understand why I cannot send email from Wordpress (ie. fail to send a password from the interface Wordpress). How about Apache config ‘ServerAdmin’ ?

    Thank you in advance for your help

    Check if the sendmail_path is set correctly.

    grep sendmail_path /etc/php5/apache2/php.ini
    

    Thank you Jesin for your quick reply.

    This is what I got when running the suggested command: sendmail_path = “usr/bin/msmtp -C /etc/.msmtp_php --logfile /var/log/msmtp.log -a gmail -t”

    However, in the /var/log/apache2/error.log, I saw this error

    sh: 1: usr/bin/msmtp: not found

    Maybe this is the reason that I cannot send email using msmtp. My user is in the group www-data and mail and I think that I set the permissions correctly. By the way, what user (role) should we use?

    Thanks again for your help. cheers,

    You missed out a / at the beginning. It should be:

    sendmail_path = "/usr/bin/msmtp -C /etc/.msmtp_php --logfile /var/log/msmtp.log -a gmail -t"
    

    Thank you so much Jesin for your great support. I added the ‘/’ as you suggested and it works like a charm.

    Hi, Thanks for the tutorial. Recently I have taken a gmail domain account (like support@domain.com). I want to send a mail from this account whenever the user register in my website. For this, I have followed the above steps and configured things as mentioned. When I run the given file sample_email.txt the mail is delivered to the user with the correct details like (from: namesupport@domain.com mailed-by : domain.com ). But when I run the php script it is giving different values (like, from : www-data “www-data@user@gmail.com via ******(some domain)” mailed-by: ******(that same name as mentioned after via) ). Please help me to correct these columns.

    Never mind, I made something wrong while configuring the php.ini file. Now it is fine. Thanks, for the article once again. :)

    Hello. how are you? I wanted to install smtp but I wanted to ask you what directory should I do the configuration? in fact I use centos 7 and wanted to make ntopng alerts by email with php. I really need your help. I am an amateur in linux I wanted to clarify it. thank you in advance!!!

    hello everyone. I came to you for help. I have a configuration problem. msmtp the configuration with the command: cat sample_email.txt | -a --debug msmtp gmail bob@domain.com, I have these following messages: msmtp: authentication failed (method PLAIN) msmtp: server message: 534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbsRV msmtp: server message: 534-5.7.14 dU_WG3tl3eq1zhs2g0IeWzF2UBdsyiayN0rxXjHZK5IhmDNxtMJD8kV-41OHGrDodKP6bI msmtp: server message: 534-5.7.14 KI5L-JUPNnEckLiT7NNiRT7T6OxwI4XIrQT6qA1ivaETCiQANV-lNKuQBpYw16v7nBTnv2 msmtp: server message: 534-5.7.14 cAp4uZjYxyfSvP3wOlWkePlajXW8pzYnglSx0ev4D6kGHrZ1izZ6K2HaBZ_RZlT4zw1XPJ msmtp: server message: 534-5.7.14 9HbBAv2SIDs73LDB8DST25zC4pZM> Please log in via your web browser and msmtp: server message: 534-5.7.14 then try again. msmtp: server message: 534-5.7.14 Learn more at msmtp: server message: 534 5.7.14 https://support.google.com/mail/answer/78754 gd10sm30481048wjb.47 - gsmtp msmtp: could not send mail (account gmail from /root/.msmtprc)

    am an amateur and my system is a Centos 7. help me.

    FOR NEWCOMERS:

    After MANY and MANY hours spent trying do it work (msmtp, sendmail, postfix, rain dance, etc) I decided to open a ticket in DO just to discover that, as a “newcomer”, my server was blocked to mail. They (DO) unblocked it and now it works.

    I am in love with DO, but, this was a big fault. Why dont just advise the “newcomers” about those restrictions?

    Support is excellent, anyway.

    Hi All, i’m a bit stuck on Ubuntu 14.04 lamp. I’ve got it working from the command line but cannot get it working from php. I’ve edited the php.ini file in /etc/php5/apache2/php.ini (which i checked was the correct one by creating a php.info page and seeing the loaded config file.

    I only get the php output error message of ‘an error occurred’ with no output in the log file i’ve created either. i’ve double checked:

    • log file location
    • permissions on /etc/.msmtp_php and /var/log/msmtp.log (both www-data:www-data)
    • restarted apache2 after editing the php.ini

    i’ve also put the msmtp settings in a global file /etc/msmtprc as well as ~/.msmtprc but without much luck (i’d tried the global one first /etc/msmtprc).

    Again it sends fine from the command line e.g. sudo echo ‘test email’ | msmtp --dubug -a gmail email@email.com

    Any ideas? thanks in advance :)

    just in case someone gets stuck on this - i checked the error log in apache (/var/log/apache2/error.log), and it turns out my permissions on /etc/.msmtp_php that was being referenced in the sendmail_path in php.ini was incorrect. some reason it was set at 660 rather than 600. after chmod’ing that, all went smoothly.

    so if you find yourself in the situation where you can send with msmtp from the command line but not from php, double check the permissions on /etc/.msmtp_php.

    Hi.

    I work with XAMPP and get the error:

    msmtp: /etc/.msmtp_php: Permission denied
    

    Owner: www-data Permission: 600

    When I changing permission to 644 I get the error:

    msmtp: /etc/.msmtp_php: must be owned by you
    

    How I can fix it?

    Change owner to daemon ☺ …

    When I try the test email i get a notification from gmail that says sign in attempt prevented.

    How do i prevent google from blocking my sign in attempt. (I don’t have google apps)

    here is what I see in console

    root@andrew:~# cat sample_email.txt | msmtp --debug -a gmail ahfridley@gmail.com ignoring system configuration file /etc/msmtprc: No such file or directory loaded user configuration file /root/.msmtprc using account gmail from /root/.msmtprc host = smtp.gmail.com port = 587 timeout = off protocol = smtp domain = localhost auth = choose user = ajhfridley@gmail.com password = * passwordeval = (not set) ntlmdomain = (not set) tls = on tls_starttls = on tls_trust_file = (not set) tls_crl_file = (not set) tls_fingerprint = (not set) tls_key_file = (not set) tls_cert_file = (not set) tls_certcheck = off tls_force_sslv3 = off tls_min_dh_prime_bits = (not set) tls_priorities = (not set) auto_from = off maildomain = (not set) from = ahfridley@gmail.com dsn_notify = (not set) dsn_return = (not set) keepbcc = off logfile = (not set) syslog = (not set) aliases = (not set) reading recipients from the command line <-- 220 smtp.gmail.com ESMTP x79sm423534qka.37 - gsmtp –> EHLO localhost <-- 250-smtp.gmail.com at your service, [104.236.122.69] <-- 250-SIZE 35882577 <-- 250-8BITMIME <-- 250-STARTTLS <-- 250-ENHANCEDSTATUSCODES <-- 250-PIPELINING <-- 250-CHUNKING <-- 250 SMTPUTF8 –> STARTTLS <-- 220 2.0.0 Ready to start TLS TLS certificate information: Owner: Common Name: smtp.gmail.com Organization: Google Inc Locality: Mountain View State or Province: California Country: US Issuer: Common Name: Google Internet Authority G2 Organization: Google Inc Country: US Validity: Activation time: Wed 16 Mar 2016 01:40:41 PM EDT Expiration time: Wed 08 Jun 2016 01:40:00 PM EDT Fingerprints: SHA1: 11:38:E6:5B:82:39:60:68:E8:CE:2E:C6:7C:E7:14:58:A8:25:5F:33 MD5: D0:F1:4C:95:E4:18:99:49:8A:5B:AC:C1:35:B0:D1:C4 –> EHLO localhost <-- 250-smtp.gmail.com at your service, [104.236.122.69] <-- 250-SIZE 35882577 <-- 250-8BITMIME <-- 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH <-- 250-ENHANCEDSTATUSCODES <-- 250-PIPELINING <-- 250-CHUNKING <-- 250 SMTPUTF8 –> AUTH PLAIN AGFoZnJpZGxleUBnbWFpbC5jb20AVGhlemFwMDc3 <-- 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbui <-- 534-5.7.14 cLVPsaV_Dt2s4pLygk43-7YGvL2gO2JsxVkGeDX0fL_-yyEGKf8pGDd0YYUkX51X_2Q7OX <-- 534-5.7.14 S-4BoTQKbASCSkWbyO9-eXN5nPWsMjqBZV_1UVqanqdldnWCEdDgbSuEWJa7Huwi1CyuWQ <-- 534-5.7.14 n2RmaEwOKolxLd611ED8SyPh6jiIVudW7WJLBME8i2s1bOpo5jYe7uZfcW7BEwUAisvVJb <-- 534-5.7.14 DBSgh8ha6wEBK5WQCIBNnQB09CbcI> Please log in via your web browser and <-- 534-5.7.14 then try again. <-- 534-5.7.14 Learn more at <-- 534 5.7.14 https://support.google.com/mail/answer/78754 x79sm423534qka.37 - gsmtp msmtp: authentication failed (method PLAIN) msmtp: server message: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbui msmtp: server message: 534-5.7.14 cLVPsaV_Dt2s4pLygk43-7YGvL2gO2JsxVkGeDX0fL_-yyEGKf8pGDd0YYUkX51X_2Q7OX msmtp: server message: 534-5.7.14 S-4BoTQKbASCSkWbyO9-eXN5nPWsMjqBZV_1UVqanqdldnWCEdDgbSuEWJa7Huwi1CyuWQ msmtp: server message: 534-5.7.14 n2RmaEwOKolxLd611ED8SyPh6jiIVudW7WJLBME8i2s1bOpo5jYe7uZfcW7BEwUAisvVJb msmtp: server message: 534-5.7.14 DBSgh8ha6wEBK5WQCIBNnQB09CbcI> Please log in via your web browser and msmtp: server message: 534-5.7.14 then try again. msmtp: server message: 534-5.7.14 Learn more at msmtp: server message: 534 5.7.14 https://support.google.com/mail/answer/78754 x79sm423534qka.37 - gsmtp msmtp: could not send mail (account gmail from /root/.msmtprc)

    So i figured out the gmail problem.

    Now when i go to the file.php on my website it says it sends successfully and same with console, but I receive no email. What’s going on?

    also the log file is empty

    Hi @ajhfridley,

    Did you allow “less secure” apps to you account as outlined here - https://support.google.com/accounts/answer/6010255?

    And also post MSMTP’s output when run from the command line after making this change. Make sure to remove your real email when posting its output.

    First of all thanks for the complete and easy understood tutorial

    I did it all good, except one thing.

    When i’m typing ‘php /var/www/html/file.php’ from my Putty console the mail is sent, it’s working like a charm.

    But when i test the script via the browser i got the “An error occured” message on my web page… and nothing is sent, no more error in my msmtp.log as well…

    Do you have any idea what is the problem ?

    Thanks again !

    Best Regards

    Hi @florent825b4310,

    I guess the ownership of the .msmtp_php file isn’t properly set. Also add ini_set(‘display_errors’,1); to the start of file.php to any PHP error messages.

    Thanks Jesin pour the reply !

    Yeah it should come from the ownership, but i don’t know how to fix it. Here the way i change the owner : chown apache:apache /etc/.msmtp_php

    i’m working under Fedora 21 and LAMP

    here the error when i’m trying it from the browser. (i replace my credentials by ***)

    msmtp: cannot connect to smtp.gmail.com, port 587: Permission denied msmtp: could not send mail (account gmail from /etc/.msmtp_php) msmtp: cannot log to /var/log/msmtp.log: cannot open: Permission denied msmtp: log info was: host=smtp.gmail.com tls=on auth=on user=*** from=*** recipients=*** errormsg=‘cannot connect to smtp.gmail.com, port 587: Permission denied’ exitcode=EX_TEMPFAIL

    I had ini_set(‘display_errors’,1); as well, but don’t know how to see more php error.

    Thanks for your concern

    I think DigitalOcean is blocking outbound SMTP ports, try this:

    yum install telnet
    telnet smtp.gmail.com 587
    chown apache:apache /var/log/msmtp.log
    

    If telnet doesn’t provide a reply, contact DO and ask them to open the ports. If you get a reply from telnet, try accessing it over the browser again and you’ll find error info in the msmtp.log file.

    Telnet seems answer Connected to smtp.gmail.com.

    i already type chown apache:apache /var/log/msmtp.log as mentionned on your excellent tutorial. But it looks like that is the same ownership problem. I got nothing in msmtp.log file.

    Once again, when i’m doing this php /var/www/html/file.php in the console, everything is good, i got the email, and the log are OK…

    Create a phpinfo() file and access it over the browser and check the “sendmail_path” value. It could be that you modified a different php.ini file because PHP command line and PHP module user different php.ini files.

    Sorry i can’t reply form your last message…

    But i already check in phpinfo.php

    By the way, i checked what user php is running as with

    <?php echo exec('whoami'); ?>
    

    It answer apache

    I really have no idea what is going on…

    Modify the “sendmail_path” to include the “–debug” argument:

    /usr/bin/msmtp --debug -C /etc/.msmtp_php --logfile /var/log/msmtp.log -a gmail -t
    

    This should display more info.

    Login to your Gmail account, access the following page and “Turn on” access for less secure apps: https://www.google.com/settings/security/lesssecureapps

    I have already turn on the less secure apps access (if i hadn’t i presume that the command line will not delivery the email).

    i try to add --debug

    still got the same error in the error_log.php

    msmtp: cannot connect to smtp.gmail.com, port 587: Permission denied
    msmtp: could not send mail (account gmail from /etc/.msmtp_php)
    msmtp: cannot log to /var/log/msmtp.log: cannot open: Permission denied
    msmtp: log info was: host=smtp.gmail.com tls=on auth=on user=florent@wayver.ca from=florent@wayver.ca recipients=florent@wayver.ca errormsg='cannot connect to smtp.gmail.com, port 587: Permission denied' exitcode=EX_TEMPFAIL
    

    Please post the output of the following commands:

    ls -l /etc/.msmtp_php
    ls -l /var/log/msmtp.log
    

    First thank you for your concern and the time you using to help me ! I appreciate it

    ls -l /etc/.msmtp_php
    
    -rw-------. 1 apache apache 170 Apr 13 16:40 /etc/.msmtp_php
    
    ls -l /var/log/msmtp.log
    
    -rw-r--r--. 1 apache apache 14299 Apr 13 18:50 /var/log/msmtp.log
    

    That is look fine as well… very strange

    @florent825b4310 The only thing left is SELinux. Check the current status:

    sudo getenforce
    

    If it returns “Enforcing”, enter

    sudo setenforce 0
    

    and try accessing the PHP file.

    Jesin, it was already done.

    But i finally found it, it was because of SELinux indeed

    i turn on httpd_can_sendmail

    So it works perfectly !

    Do you think is it secure enough ?

    Thank you very much Jesin ! Great tutorial, great support !

    Thanks a great find Florent and yes it is mush more secure than entirely turning off SELinux.

    I found more info about this Boolean here - http://linux.die.net/man/8/sendmail_selinux

    This comment has been deleted

      Hi Jesin A, Thank you for the great tutorial. I followed your steps to config Gmail with msmtp. The sending works from shell, even from php, but every time I send an email through php I receive “504 Gateway Time-out”, but the email is sending and is received every time. I run Centos 6.7 with LEMP. My google-fu was to so helpful with me these days.

      Nevermind. I configured it with zoho mail. My thoughts are that this is related to IPv6. my telnet smtp.gmail.com 587

      Trying 2607:f8b0:400d:c02::6d...
      telnet: connect to address 2607:f8b0:400d:c02::6d: Connection timed out
      Trying 173.194.205.108...
      Connected to smtp.gmail.com.
      Escape character is '^]'.
      220 smtp.gmail.com ESMTP a31sm3014038qga.34 - gsmtp
      
      

      Hi @calincristianiu,

      You can configure CentOS to prefer IPv4 over IPv6 by following this guide - https://community.rackspace.com/products/f/25/t/5110. This way, the connections would be much faster.

      And I think DO is blocking port 587 for your account for IPv6 connections as it works for me.

      $ telnet 2607:f8b0:400d:c02::6d 587
      Trying 2607:f8b0:400d:c02::6d...
      Connected to 2607:f8b0:400d:c02::6d.
      Escape character is '^]'.
      220 smtp.gmail.com ESMTP w5sm6348392qhc.15 - gsmtp
      
      

      Is Anybody here with google account suspension mail while doing this?? My google account has been suspended. Does it have to do anything with this?

      Hi,

      I have gone through all of the comments and followed this tutorial but can’t get my PHP form to process and send the email.

      After installing MSMTP I have modified the PHP ini file and checked that it was the correct one using phpinfo()

      I can send an email from the terminal and it works fine. The PHP form processes online but nothing gets sent even though I get an “email sent” with the test.php.

      I am using Ubuntu 14.16 and have checked the log file - there are no errors.

      I am wondering if having additional dirs that are preventing the overriding the apache2/php.ini file such as:

      /etc/php5/apache2/conf.d/05-opcache.ini, /etc/php5/apache2/conf.d/10-pdo.ini, /etc/php5/apache2/conf.d/20-curl.ini, /etc/php5/apache2/conf.d/20-gd.ini, /etc/php5/apache2/conf.d/20-json.ini, /etc/php5/apache2/conf.d/20-mysql.ini, /etc/php5/apache2/conf.d/20-mysqli.ini, /etc/php5/apache2/conf.d/20-pdo_mysql.ini, /etc/php5/apache2/conf.d/20-readline.ini, /etc/php5/apache2/conf.d/20-snmp.ini

      Also, could it be perhaps that I have to add something to my process-form.php?:

      <?php $event_date = $_POST[‘event_date’]; $name = $_POST[‘full_name’]; $event_type = $_POST[‘event_type’]; $telephone = $_POST[‘telephone’]; $email = $_POST[‘email’];

      $email_from = ‘gmail I set up form msmtp goes here’;

      $email_subject = "New Form submission from your website";
      
      $email_body = "You have received a new message via your websites form from $name.\n".
                              "The date requested for the event is:\n     $event_date\n".
          
      "The type of event is:\n $event_type \n".
          
      "The customers contact telephone number is:\n $telephone \n".
      
      "From:\n $email \n".
      

      $to = “myclientsemailaddress@gmail.com”; $headers = “From: $email_from \r\n”; $headers = “Reply-To: $email \r\n”; mail($to,$email_subject,$email_body,$headers);

      //Load thank you page once form is submitted

      header (‘Location: contact-thank-you.html’); exit();

      ?>

      <?php

      function IsInjected($str) { $injections = array(‘(\n+)’, ‘(\r+)’, ‘(\t+)’, ‘(%0A+)’, ‘(%0D+)’, ‘(%08+)’, ‘(%09+)’ );

      $inject = join('|', $injections);
      $inject = "/$inject/i";
       
      if(preg_match($inject,$str))
      {
        return true;
      }
      else
      {
        return false;
      }
      

      }

      if(IsInjected($visitor_email)) { echo “Bad email value!”; exit; }

      error_reporting(-1);

      ?>

      Sorry I am relatively new to all this and have been struggling for several days.

      Thanks!

      Hi @seanroughton,

      The code isn’t formatted properly, can you paste it on pastebin and share its URL here.

      Sorry here is the code for my PHP - http://pastebin.com/km8QfjTc

      However, the test.php does not send an email but also says it’s successful.

      Thanks.

      The script is redirecting you to contact-thank-you.html before any errors can be displayed. So comment out line 33 by adding // to its front.

      Also add a period before = on line 25.

      $headers .= "Reply-To: $email \r\n";
      

      Thanks.

      I have modified the script as you’ve suggested but I am getting no error reporting once the form is submitted, it just goes to a blank white page.

      The PHP works fine and sends the email (albeit very slowly and sent to spam) if I use this:

      mail($to,$email_subject,$email_body,$headers, ‘-f myclientsemail@gmail.com’);

      But this is the method I was using before I installed MSMTP and the problem seems to lie in the MSMTP configuration, I’d imagine.

      Are you having a from mywebsiteemail@gmail.com configuration in /etc/msmtprc?

      You can remove the // on line 33 as it is working now.

      Hey,

      this is a great tutorial, however i cant send emails using http://162.243.202.249/ankitesh.php but when i type php /var/www/html/ankitesh.php , the mail is sent.

      please help me out

      Hi @jhaankitesh,

      I checked the sendmail_path value on your info.php page and it was set to /usr/local/bin/msmtp -t -i, are you sure this is correct on your setup?

      screwed up with the old droplet, created a new one http://128.199.116.49/ and info file at http://128.199.116.49/test.php

      i am getting the error

      msmtp: account default not found: no configuration file available msmtp: account default not found: no configuration file available

      please help me out…please

      Where have you created the msmtprc file? Please paste its contents (after removing personal info) and also its file permissions with ls -l.

      Hello,

      Thanks for the script guidelines. Works perfectly but execution time is very much slow. Also when i am trying to execute using command line, gives me this error

      “sh: 1: /usr/sbin/sendmail: not found”

      Please let me know where i am lacking in configuration.

      Hi @ishanupadhyaya,

      PHP uses different config files for web and comand-line executions. Edit /etc/php5/cli/php.ini and modify the sendmail_path directive.

      hi
      I’ve tried installing but cant find the specified file in /etc/msmtprc

      Hi @gekadi,

      The /etc/msmtprc file should be manually created with the settings in this article.

      Hi to everyone

      Thanks for the tutorial, it’s very clear and easy to follow ,

      Just one question Why take so long to send the email around 1-2 minutes?

      Any suggestion to solve this?

      @jesin

      account  gmail
      host   smtp.gmail.com
      port   587
      from   xxxx@gmail.com
      user   xxxx@gmail.com
      password  xxxxxx
      auth   on
      tls   on
      tls_trust_file /etc/ssl/certs/ca-certificates.crt
      
      # Default account to use
      account default : gmail
      

      When tested echo Test mail | msmtp --debug -a gmail xxxx@gmail.com, mail was sent successfully.

      However, I’m struggling to make my contact form script works.

      <?php
      if($_POST)
      {
          $to_Email       = "xxxx@gmail.com";
          $subject        = 'Ah!! You got Mail...';
      
          $user_Name        = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
          $user_Email       = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
          $user_Message     = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
          
          $headers = 'From: '.$user_Email.'' . "\r\n" . 
          'Reply-To: '.$user_Email.'' . "\r\n" .
          'X-Mailer: PHP/' . phpversion();
          
          $sentMail = @mail($to_Email, $subject, $user_Message .'  -'.$user_Name, $headers);
          
          if(!$sentMail)
          {
              $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
              die($output);
          }else{
              $output = json_encode(array('type'=>'message', 'text' => 'Hello, <b>'.$user_Name .'</b>, thank you for your email. Will get back to you as soon as possible.'));
              die($output);
          }
      }
      ?>
      

      What am I missing here? Any advice is much appreciated!

      PS: This is the same script that works on the other shared hosting and I’m struggling to make it work here at DO.

      Hi @yansusanto,

      Create a phpinfo() file and access it over the browser. Check the sendmail_path file, does it contain the path to msmtp?

      Also check the permissions of the msmtprc file.

      I got problem too, but with this message below when test to send an email by command line.

      /usr/bin/msmtp: Permission denied

      what am I doing wrong with the permission??

      I’ve tried this method. It sends an email with this terminal command “cat sample_email.txt | msmtp --debug -a gmail bob@domain.com”, but when I implemented the mail() in php it does not send. Also, it does not send an error.

      Dear All,

      I am a newbie and using Debian 8 and NGINX for my web server, just followed this tutorial step by step and finally I still unable to send an email. For testing, I run this command;

      cat sample_email.txt | msmtp --debug -a gmail wahyu.wardana@yahoo.com

      then I got this message:

      -bash: /usr/bin/msmtp: Permission denied

      What’s the problem, can you help me, please?

      Thank you.

      Verify the permissions for the folder /usr/bin/msmtp. Maybe you don´t have permissions to read o execute over that folder.

      Excellent tutorial!!! I followed the steps and worked like a charm. But I want to send emails from different senders from my website. eg. If the user goes to www.mypage.com/A.php I want to send a mail from mailA@gmail.com and If the user goes to www.mypage.com/B.php I want to send a mail from mailB@gmail.com

      In /etc/.msmtp_php I defined both accounts

      account gmailA
      ...
      user mailA@gmail.com
      from mailA@gmail.com
      password XXXXX
      
      account gmailB
      ...
      user mailB@gmail.com
      from mailB@gmail.com
      password XXXXX
      

      In sendpath I defined only gmailA

      sendmail_path = "/usr/bin/msmtp -C /etc/.msmtp_php --logfile /var/log/msmtp.log -a gmailA -t"
      

      and all the mails sends with FROM: mailA@gmail.com Which is fine but I want that sometimes the sender is mailB@gmail.com

      I use this headers in mail()

       $header.= "From: mailB@gmail.com \r\n" .
          "Reply-To: mailB@gmail.com \r\n";  
      

      but sender keep being mailA@gmail.com

      is there any way to define another account in sendmail_path so I can “choose” which one to use??

      Hi,

      first of all thanks for this and all the other great tutorials!

      However, with this one I have one issue I could not solve.

      If I do: cat sample_email.txt | msmtp --debug -a gmail bob@domain.com

      There is a lot of console output, ending with: reading recipients from the command line

      If I wait long enough (approx. 2 minutes) I receive the mail. However, the problem propagates to phps mail function. This means, if a user fills out a contact form he has to wait for approx. 2 minutes until he receives feedback.

      (When googling, I usually find that the /etc/hosts file needs to be properly set, however, this is not the issue here).

      Any ideas?

      Five years later and this article is still helpful. Incase anyone else is still reading and has any issues like with security warning, follow these steps:

      1. Setup HTTPS
      2. Setup UFW with correct ports
      3. Create an secondary email account (name it something like auto.response@gmail.com).
      4. Set PHP mail headers as follows:
        mail ( $to, $subject, $html_email, getMailHeaders() );
        function getMailHeaders() {
          $headers = "From: No-Reply <example@gmail.com>\r\n";
          $headers .= "Return-Path: Name <example@gmail.com>\r\n";
          $headers .= "Bcc: Name <example@gmail.com>\r\n";
          $headers .= "MIME-Version: 1.0\r\n";
          $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
          $headers .= "X-Priority: 3\r\n";
          $headers .= "X-Mailer: PHP". phpversion() ."\r\n";
          return $headers;
        }
      

      Following these steps all emails have no security warning and are not marked as spam.

      I’m close to getting this working, but can’t get the last step. This line sends the email just fine:

      cat sample_email.txt | msmtp --debug -a gmail bob@domain.com
      

      But when I try to execute it from a php file (either in the command line with “php /var/www/file.php” or in the web browser) it doesn’t send at all. Oddly, the command line returns “Email successfully sent” while the web browser says “An error occurred.” It seems like something is wrong with the php config. Any ideas?

      Thanks for the awesome tutorial! I have found tons of new and useful information here and it worked.

      Had the same issue with PHP 8.2 of emails sending in SSH, but not from the PHP file itself. Nothing in the logs.

      Ultimately gave up and just decided to send emails like this:

      exec('echo -e "To: alice@email.com\nSubject: Your subject \n\nYour message body" | msmtp -a gmail bob@email.com');
      

      Actually, this didn’t work either. I ended up going down a deep rabbit hole of apparmor permissions, etc.

      Here’s my recommandations:

      • Check /var/log for last modified file when you execute the PHP script to see which files are logging errors
      • Run the PHP script in CLI as www-data (or whatever your webserver runs as), since it gives more detials than just “an error occurred”:
      sudo -u www-data php mail.php
      

      In my case, these were the changes needed:

      sudo nano /etc/apparmor.d/usr.bin.msmtp
      

      Then add:

      /etc/.msmtp_php r
      

      Reload apparmor:

      sudo apparmor_parser -r /etc/apparmor.d/usr.bin.msmtp
      
      sudo chmod 600 /etc/.msmtp_php
      

      Good luck!

      I ended up going down a deep rabbit hole of apparmor permissions, etc.

      Here’s my recommandations:

      • Check /var/log for last modified file when you execute the PHP script to see which files are logging errors
      • Run the PHP script in CLI as www-data (or whatever your webserver runs as), since it gives more detials than just “an error occurred”:
      sudo -u www-data php mail.php
      

      In my case, these were the changes needed:

      sudo nano /etc/apparmor.d/usr.bin.msmtp
      

      Then add:

      /etc/.msmtp_php r
      

      Reload apparmor:

      sudo apparmor_parser -r /etc/apparmor.d/usr.bin.msmtp
      
      sudo chmod 600 /etc/.msmtp_php
      

      Good luck!

      Try DigitalOcean for free

      Click below to sign up and get $200 of credit to try our products over 60 days!

      Sign up

      Join the Tech Talk
      Success! Thank you! Please check your email for further details.

      Please complete your information!

      Become a contributor for community

      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

      DigitalOcean Documentation

      Full documentation for every DigitalOcean product.

      Resources for startups and SMBs

      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

      Get our newsletter

      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

      New accounts only. By submitting your email you agree to our Privacy Policy

      The developer cloud

      Scale up as you grow — whether you're running one virtual machine or ten thousand.

      Get started for free

      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

      *This promotional offer applies to new accounts only.