Why sending email using PHP from localhost fails

One of the easy tasks PHP web developers can perform is send emails. While sending emails from a production server works, it usually fails when sent from localhost.

There are many ways to send emails using PHP. This article focuses on using the native PHP function mail(), and how that fails from localhost.

Why does it fail?

Sending email from localhost usually fails because of DNS. When you use the mail() function the system opens an SMTP connection to the server of the email recipient. The very first line of communication under the SMTP protocol is your system hailing with "HELO localhost". The recipient's server would expect a regular domain (example.com) instead of localhost. That is one reason the recipient's server may reject your email.

Your email may go through, but chances are you get high spam score if the recipient's server uses spam protection software. High spam score means that your email may be rejected.

Your email may still go through, but some web servers check if the domain of the "Sender" email address corresponds to your connection's IP. For example assume your sender's email address is name@example.com . Gmail or other popular mail services will require "example.com" to resolve to your connection's IP before allowing the email to go through.

How to send emails from localhost successfully

One simple way to successfully send an email from localhost is to open an SMTP connection to a regular server and let that server do the job for you. In this case the server would be called a Mail Transfer Agent or MTA, and it will probably succeed because it has all the DNS settings properly set.

A popular PHP extension that handles all that for you is PHPMailer.

If you still want to use the native mail() function you can adjust your php.ini settings to send your emails through an MTA. You can find some useful comments here.

If you are using XAMPP or MAMP look into the documentation for guidance on how to set up your php.ini file along with other mail services so that you can use the native mail() function.

If you are using WordPress look up the documentation for "phpmailer".

If you are using Joomla you can set the SMTP credentials from the administrator's control panel: Global Configuration > Server > Mail Settings

If you are using Drupal look up the module "SMTP Authentication Support".