PHP Tutorial PHP Advanced PHP References

PHP - Sending Emails



The PHP mail() function allows us to send emails directly from a script. The behavior of this function is affected by settings in php.ini. Hence, the php.ini file must be configured correctly with the details of how the system should send emails.

PHP mail() function

The PHP mail() function is used to send mail directly from a script.

Syntax

mail(to, subject, message, additional_headers, additional_params)

Parameters

to Required. Specify receiver or receivers of the mail.
subject Required. Specify the subject of the email to be sent. This parameter cannot contain any newline character.
message

Required. Specify the message to be sent. Each line should be separated with a CRLF (\r\n). Lines should not be larger than 70 characters.

Windows only: If a full stop is found on the start of a line, it is removed. To counter-act this, replace these occurrences with a double dot.
additional_headers

Optional. Specify string or array to be inserted at the end of the email header. This is typically used to add extra headers (From, Cc, and Bcc). Multiple extra headers should be separated with a CRLF (\r\n). If an array is passed, its keys are the header names and its values are the respective header values.

When sending mail, the mail must contain a From header. This can be set with the additional_headers parameter, or a default can be set in php.ini.
additional_params Optional. Specify additional flags to pass as command line options to the program configured to be used when sending mail, as defined by the sendmail_path configuration setting. For example, this can be used to set the envelope sender address when using sendmail with the -f sendmail option.

Return Value

Returns true if the mail was successfully accepted for delivery, false otherwise. Please note that even if the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.

Example: sending mail

In the example below, the mail() function is used to send a simple mail.

<?php
//the message
$message = "Line 1\r\nLine 2\r\nLine 3";

//in case of lines larger than 70 characters
//wordwrap() function can be used
$message = wordwrap($message, 70, "\r\n");

//the subject
$subject = "My Subject";

//sending mail
$retval = mail('user@example.com', $subject, $message);
         
if($retval == true) {
  echo "Message sent successfully!";
} else {
  echo "Message could not be sent!";
}
?>

Example: sending mail with extra headers

In the example below, extra headers like From, Reply-To and X-Mailer are added.

<?php
$to      = "user@example.com";
$subject = "My Subject";
$message = "Hello World!";
$headers = 'From: webmaster@example.com'."\r\n".
    'Reply-To: webmaster@example.com'."\r\n".
    'X-Mailer: PHP/'.phpversion();

//sending mail
$retval = mail($to, $subject, $message, $headers);

if($retval == true) {
  echo "Message sent successfully!";
} else {
  echo "Message could not be sent!";
}
?>

Example: sending mail with extra headers as array

Consider the example below, where extra headers are added as an array.

<?php
$to      = "user@example.com";
$subject = "My Subject";
$message = "Hello World!";
$headers = array('From' => 'webmaster@example.com',
                 'Reply-To' => 'webmaster@example.com',
                 'X-Mailer' => 'PHP/' . phpversion()
                );

//sending mail
$retval = mail($to, $subject, $message, $headers);

if($retval == true) {
  echo "Message sent successfully!";
} else {
  echo "Message could not be sent!";
}
?>

Example: sending mail with an additional command line parameter

Consider the example below which shows how to add an additional command line parameter with this function.

<?php
$to      = "user@example.com";
$subject = "My Subject";
$message = "Hello World!";

//sending mail
$retval = mail($to, $subject, $message, null,
             '-fwebmaster@example.com');

if($retval == true) {
  echo "Message sent successfully!";
} else {
  echo "Message could not be sent!";
}
?>

Send HTML email

To send HTML message, the Content-type header must be set.

<?php
//specifying multiple recipients
$to = 'john@example.com, marry@example.com';

//subject
$subject = 'Birthday Reminders for July';

//the message
$message = '
<html>
<head>
  <title>Birthday Reminders for July</title>
</head>
<body>
  <p>Here are the birthdays upcoming in July!</p>
  <table>
    <tr>
      <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
    </tr>
    <tr>
      <td>John</td><td>15th</td><td>July</td><td>1970</td>
    </tr>
    <tr>
      <td>Marry</td><td>25th</td><td>July</td><td>1973</td>
    </tr>
  </table>
</body>
</html>
';

//to send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';

//additional headers
$headers[] = 'From: Birthday Reminder <me@example.com>';
$headers[] = 'Cc: user3@example.com';
$headers[] = 'Bcc: user4@example.com';

//sending mail
$retval = mail($to, $subject, $message, implode("\r\n", $headers));

if($retval == true) {
  echo "Message sent successfully!";
} else {
  echo "Message could not be sent!";
}
?>

Send email with attachment

To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries.

A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email's final section must also end with two hyphens.

<?php
//specifying multiple recipients
$to = 'john@example.com, marry@example.com';
$message = "Hello World!";
$subject = "My Subject";

$LE  = "\r\n";
$uid = md5(uniqid(time()));
$filePath = "path to the file";

//checking if the mail contains attachment
$withAttachment = ($filePath !== NULL && file_exists($filePath));

//getting the file information
//reading the file & base64_encode content
if($withAttachment){
  $fileName   = basename($filePath);
  $fileSize   = filesize($filePath);
  $handle     = fopen($filePath, "r");
  $content    = fread($handle, $fileSize);
  fclose($handle);
  $content = chunk_split(base64_encode($content));
}

//setting the headers
$header  = "From: My Name <me@example.com>$LE";
$header .= "Reply-To: webmaster@example.com $LE";
$header .= "MIME-Version: 1.0$LE";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"$LE";
$header .= "This is a multi-part message in MIME format.$LE";
$header .= "--".$uid."$LE";
$header .= "Content-type:text/html; charset=UTF-8$LE";
$header .= "Content-Transfer-Encoding: 7bit$LE";
$header .= $message."$LE";

//additional headers if having attachment
if($withAttachment){
  $header .= "--".$uid."$LE";
  $header .= "Content-Type: application/octet-stream; name=\"".$fileName."\"$LE";
  $header .= "Content-Transfer-Encoding: base64$LE";
  $header .= "Content-Disposition: attachment; filename=\"".$fileName."\"$LE";
  $header .= $content."$LE";
  $header .= "--".$uid."--";
}

//sending mail
$retval = mail($to, $subject, $message, $header);

if($retval == true) {
  echo "Message sent successfully!";
} else {
  echo "Message could not be sent!";
}
?>