PHP Mail Function - Sending E-mail with PHP

The PHP mail function is what we use if we want to send email using a PHP script. This function is appropriately named mail, and when invoked with the right parameters, it allows us to send an email fairly easily.

For the PHP mail function to work properly, PHP itself must be configured to use a mail transfer agent. We will look more at that below. Right now let's get into the syntax of the PHP mail function.

PHP Mail Function Syntax

The syntax for the simplest form of the PHP mail function is as follows:

mail(to, subject, message, headers);

Each parameter should be self-explanatory except the headers parameter. The headers parameter is used to specify additional information such as the From, Cc and Bcc fields. For the simple example below we will be using the headers parameter only to add where the email is coming From.

PHP mail Function Example

You can send an email using the simple script shown below:

<?php
 
// specify who the email is going to
$to = "webmaster@tutorialarena.com";
 
// specify the subject
$subject = "Test Email";
 
// specify the message
$message = "This is a sample email message body.";
 
// specify who it is coming from
$from = "someone@somewhere.com";
 
// correctly set the headers
$headers = "From: $from";
 
// send the email
mail($to, $subject, $message, $headers);
 
?>

If we ran that script, an email would be sent to someone@somewhere.com with the originating sender being listed as webmaster@tutorialarena.com. Pretty simple huh? It is really that easy to send an email using PHP! The PHP mail function takes care of all the hard work for us.

Problems using the mail function in PHP

For the PHP mail function to work, PHP itself needs to be configured to use an existing mailing system on the server. That is, in the PHP configuration, there needs to be a directive to tell the PHP interpreter what program it should use to send the email. The simplest way is to configure PHP to use sendmail if you are on a Linux server.

If you are on a Linux/Unix server, edit your php.ini file and ensure there is a line in it which says something like:

sendmail_path = /usr/sbin/sendmail -i -t

This is the line which tells PHP the external program it should use to send the email.

If you encounter any issues when sending email using PHP, chances are there is an issue with your PHP configuration. Ensure that mail is properly configured in your PHP settings and check the error logs for other hints as to the cause of the problem. We hope this tutorial on the PHP mail function has been helpful.

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...