PHP Mail

How to send email using php

We are discussing how to send email using PHP in this article. In order to do this we are using PHP mail function.

What is PHP mail?

PHP mail is an in built PHP function that is used to send emails from PHP scrips.

Php mail function accepts following parameters.

  • Email address
  • Subject
  • Message
  • CC or BCC email addresses
  • Headers

Sending email using PHP mail

The php mail function has following syntax.

<?php
mail($to,$subject,$message,[$headers],[$parameters]);
?>

Parameters used in php mail

Let’s look at each of the parameters passed in above syntax

  • $to is the email address of the email recipient
  • $subject is the email subject
  • $message is the content or message to be sent
  • [$headers] is an optional parameter. It can be used to include information such as CC, BCC, Reply-To etc.
    • CC is the acronym for Carbon Copy. It is used to send a copy to interested person. (ex: a complaint email sent to a company can also be sent to the complaints board using CC)
    • BCC is the acronym for Blind Carbon Copy. It is similar to CC. But the email addresses included in the BCC section will not be shown to the other recipients.

Php mail example

  • Basic example
<?php     
$to = 'receiver@domain.com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: noreply@company.com';
mail($to_email, $subject, $message, $headers);
?>

Result:

If email need to be sent to multiple recipients, it can be done by using as follows.

<?php     
$to = 'receiver1@domain.com, receiver2@domain.com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: noreply@company.com';
mail($to, $subject, $message, $headers);
?>
  • Advanced Example

To make the email more efficient and more secure, additional parameters can be used as follows.

<?php
$to      = 'john@example.com, abby@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = array(
    'To' => 'John <john@example.com>, Abby <abby@example.com>',
    'From' => '<Webmaster> webmaster@example.com',
    'Reply-To' => 'webmaster@example.com',
    'X-Mailer' => 'PHP/' . phpversion()
);
mail($to, $subject, $message, $headers);
?>

In addtion to that, if the email need to be send to CC, and BCC recipients, it can be done as follows.

<?php
$to      = 'john@example.com, abby@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = array(
    'To' => 'John <john@example.com>, Abby <abby@example.com>',
    'From' => 'Webmaster <webmaster@example.com>',
    'Reply-To' => 'Webmaster <webmaster@example.com>',
    'CC' => 'Christi <christi@example.com>, Emma <emma@example.com>',
    'BCC' => 'Oliver <oliver@example.com>, Emma <jacob@example.com>',
    'X-Mailer' => 'PHP/' . phpversion()
);
mail($to, $subject, $message, $headers);
?>

You can learn more about PHP Mail function in official documentation.