PHP Mail Function: Simple mail, HTML mail

PHP Mail

  • In PHP, the mail function is used to send emails directly from the script.
  • The mail function in PHP accepts these parameters.
    • Email address
    • Subject
    • Message
  • PHP must be configured correctly in the php.ini file with the details of how your system sends an email.

Syntax for PHP mail function is:

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

Here,

to is the mail receiver. It is mandatory.

subject is the subject of the email to be sent. It is mandatory.

message is the message to be sent. It is mandatory.

headers is optional. Specifies an additional header, like from, Cc and Bcc. It should be separated with CLRF (\r\n).

parameters are optional.

In PHP, whenever the mail function is called it will send the email. If email is sent successfully it will return true, otherwise false.

Example 1:- Sending mail with extra headers.

<?php
	$to = 'testemail@thecodetutorial.com';
	$subject = 'The Main Subject';
	$message = 'The World is great place to live.';
	$headers = ' From: sender@thecodetutorial.com ' . "\r\n" .
    ' Reply-To: reply@thecodetutorial.com ' . "\r\n" .
	mail($to, $subject, $message, $headers);
?>

Above example will send the email to testemail@thecodetutorial.com with following options

sender(From): sender@thecodetutorial.com

reply to: reply@thecodetutorial.com

Example 2:- Sending HTML mail.

<?php
$to = 'to@thecodetutorial.com';
$subject = 'The Festivals of India in January 2020';

$message = '
<html>
<head>
  <title>The Festivals of India in January 2020</title>
</head>
<body>
  <p>Here are The Festivals of India coming in January 2020!</p>
  <table>
    <tr>
      <th>Festival Name</th><th>Day</th><th>Month</th><th>Year</th>
    </tr>
    <tr>
      <td>Makar Shankranti</td><td>14th</td><td>January</td><td>2020</td>
    </tr>
    <tr>
      <td>Republic Day</td><td>26th</td><td> January</td><td>2020</td>
    </tr>
  </table>
</body>
</html>
';

$headers = ' From: falgun@thecodetutorial.com ' . "\r\n" .
    ' Cc: jenny@thecodetutorial.com ' . "\r\n" .

mail($to, $subject, $message, $headers);
?>

Above example will send the email in html format.