PHP Mail Function Example

In this example, we will see how we can send emails with PHP. After seeing this example, you will be able to send emails programmatically, which is especially useful in scenarios like the following:

  • Registration confirmation.
  • Password recovery.
  • Notification delivery.

And any other scenario where a service needs to contact a user.

PHP has a built-in function called mail that will do all the job but, first, we have to make some configurations in order to make this function work.

For this tutorial, we will use:

  • Ubuntu (14.04) as Operating System.
  • Apache HTTP server (2.4.7).
  • PHP (5.5.9).
  • sSMTP (2.64), a lightweight MTA (Mail Transfer Agent).
You may skip environment preparation and jump directly to the beginning of the example below.

1. Preparing the environment

1.1. Installation

Below, the commands to install Apache and PHP are shown:

sudo apt-get update
sudo apt-get install apache2 php5 libapache2-mod-php5
sudo service apache2 restart

Now, we install sSMTP:

sudo apt-get install ssmtp

With this MTA, now, we will be able to send mails from our machine, to a SMTP server. In other words, we can make a SMTP server (like Gmail’s, Outlook’s, etc.) deliver the mails we want to send.

1.2. sSMTP configuration

The sSMTP configuration consists of two things:

  • Defining the SMTP service we are going to use.
  • Provide credentials for that service.

In this example, we will use Google’s Gmail SMTP server., and supposing that we have an account named, with mygmailpassword as password.

So, taking that into account, the /etc/ssmtp/ssmtp.conf file will remain as:



This is what we are setting:

  • UseSTARTTLS: necessary for using Gmail’s SSL/TLS sever.
  • mailhub: the smtp server itself, in port 587, for SSL/TLS.
  • AuthUser and AuthPass: credentials for loging in Gmail.

Note: take care of who has access to this file – anyone having access to the file, can access the mail account set.

1.3. PHP configuration

The last step, is to make PHP now how to use sSMTP. For that, we have to specify the path to sSMTP executable, in PHP config file, /etc/php5/apache2/php.ini file:


sendmail_path = /usr/sbin/sendmail

Don’t forget to restart Apache after making any change in PHP configuration:

sudo service apache2 restart

2. PHP mail sending script

The PHP code is all about calling a function, named mail. Here an example that sends a mail to someone, with a subject and the message itself:



$to = ',';
$subject = 'Mail from PHP';
$message = "Hi,\r\nThis mail has been sent using PHP!";

$success = mail($to, $subject, $message);

if ($success) {
    $response = 'Message has been sent successfully.';
} else {
    $response = 'The message could not be sent.';

echo $response;

There are a few things that have to be taken into account:

  • It is possible to set multiple mails to send the mail to, separated by commas, as in the example above.
  • mail function does not perform any encoding. This can be a problem, that we will see below how to deal with.
  • The lines must be separated with Windows line ending format, i.e., the CRLF: '\r\n'.
  • Unfortunately, mail function only returns a boolean value so, if something goes wrong, we cannot have any details at runtime.

Mail function has two more optional parameters: for setting additional headers, and for setting additional parameters. The first one is to add additional headers, as we would do, for example, in a HTML page. The last one is, actually, a MTA command line parameter, used to pass additional flags and commands.

Let’s see how can we use these additional options.

2.1. Setting additional headers

Consider the following scenario: we have a system that sends greetings to the users registered within, each one in the language set by the user. If we have, for example, a Chinese user, the message body would be:


$message = '你好'; // 'Hello' in Chinese.

With the example we saw above, the result would be an ugly string of characters that don’t match with the expected Chinese characters. For a scenario like this, is not enough to rely the encoding only in the language setting. The solution would be to encode the message properly, encoding it to UTF-8, and, for that, we have to set the header manually.

For that, we need to perform two additional steps:


$headers = 'Content-Type: text/plain; charset=UTF-8';

$success = mail($to, $subject, $message, $headers);

Quite simple: define the headers, and pass them to the function. If we try now the script, we will receive a mail with those nice Chinese characters.

It is also usual to use this additional headers, for example, to add carbon copies (cc) and blind carbon copies (bcc).

Note: Multiple headers must be separated as same as new lines in the message, with a CRLF.

2.2. Setting additional parameters

As told before, when we are setting additional parameters, we are actually passing instructions that will be executed by the server, te binary we set to sendmail_path, in php.ini.

For example, we could set the verbose mode, to see how is going the whole process, which can be useful for troubleshooting.

For this, we just declare another variable, for the parameters, and we pass it as last parameter to the function:


$parameters = '-v';

$success = mail($to, $subject, $message, $headers, $parameters);

If we execute now the script, we will see the whole process: from the initial handshake with the server, to the connection close.

In this case, to pass several parameters, they must be separated by a blank space.

You can see the whole list of available options in sSMTP manual:

man ssmtp

3. Troubleshooting

If you have not been able to make this example work, in this section we are going to see which can be the possible causes, and finding solutions for them.

3.1. Set verbose mode

Before doing anything else, the first recommended step would be to set the verbose mode, to see in detail what’s happening. You can see how to do it in section 2.2.

3.2. Login is rejected by SMTP server

It may occur that Gmail considered the login attempt through sSMTP as insecure or suspicious, because of trying to login using an external service or app.

To confirm that this is the problem, login into the account you set in sSMTP configuration file, and you should have received and email from Google with a subject similar to:

Suspicious sign in prevented.

To disable this security measure, in Gmail, go to My Account/Sign-in & security, and in Connected apps & sites section, enable the “Allow less secure apps” toggle to “on”.

3.3. Firewall is filtering outgoing traffic

Maybe, a firewall is filtering the connection. Normally, by default, firewalls do not filter outgoing traffic, but it can be a possibility. Check that you don’t have any firewall filtering outgoing traffic that would affect to this example (remember that we configured the MTA to use the port 587).

3.4. Check PHP error log

If it continues not working, check the PHP error log, to see which is the error thrown by PHP, to get more hints of which can be the error. By default, the error log is located in /var/log/apache2/error.log.

4. Alternatives to sSMTP

For this example, we have chosen sSMTP as it is the easiest and fastest way to deliver mails, only needing the simple configuration we saw in section 1.2, and also because it is very light; is not using daemons, and its impact in CPU and memory is negligible.

But, if you are looking for a more advanced, full-featured MTA, Postfix and Exim are probably the most used ones.

5. Summary

In this example, we have seen how to send mails with PHP, which is pretty simple – only a function call is needed. But we have also seen that, that alone is not enough, and that a MTA is needed, to connect with the SMTP server we are using. We have also analysed the most common errors that we can face in this task, and how to solve them, apart from the problem that can suppose the sending of not properly encoded mails.

6. Download the source code

This was an example of mail sending with PHP.

You can download the full source code of this example here: PHPMailFunctionExample
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button