How to Send Email With Extra Headers in PHP

Sending email with PHP Is easy—and limited

PHP email with extra headers
Was this page helpful?


Sending emails with PHP is simple; all you need is a function and three arguments. That's not all there is to normal email messages, however. Any look closer than a mere glance will reveal that this use of PHP email lacks some basic functions. For example, it doesn't set the  From: header line. In keeping with PHP's reputation for ease of use, however, that's a quick fix: Just add another argument to specify extra headers such as X-Mailer, Cc:, and, of course, From:.

Note: If you specify more than one extra header, make sure you separate the header lines with \r\n to make sure they work as intended.

Adding Extra Headers in PHP

A simple message with extra headers might look like this:

<?php
$to = "recipient@example.com";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";
$headers = "From: sender@example.com\r\n". 
"X-Mailer: php";
if (mail($to, $subject, $body, $headers)) {   
echo("<p>Message sent!</p>");  
}
else {
echo("<p>Message delivery failed...</p>");  
}
?>

PHP Email With Extra Headers Using PEAR Mail

You also can insert extra headers when using PEAR Mail to send email, of course:

<?php
require_once "Mail.php";
$from = "Stephanie Sender <sender@example.com>";
$to = "Richard Recipient <recipient@example.com>";
$subject = "Hi!"; $xmailer: "php"
$body = "Hi,\n\nHow are you?";
$host = "ssl://mail.example.com";
$port = "465";
$username = "smtp_username";
$password = "smtp_password";
$headers = array ('From' =>
$from, 'To' =>
$to, 'Subject' =>
$subject, 'X-Mailer' =>
$xmailer);
$smtp = Mail::factory('smtp', array ('host' =>
$host, 'port' =>
$port, 'auth' => true, 'username' =>
$username, 'password' =>
$password));
$mail = $smtp->send(
$to,
$headers,
$body);
if (PEAR::isError($mail)) {
echo("<p>". $mail->getMessage(). "</p>");  
}
else {
echo("<p>Message successfully sent!</p>");  
}
?>
$subject = "Hi!";
$xmailer: "php"
$body = "Hi,\n\nHow are you?";
$host = "ssl://mail.example.com"; $port = "465";
$username = "smtp_username";
$password = "smtp_password";
$headers = array ('From' =>
$from, 'To' =>
$to, 'Subject' =>
$subject, 'X-Mailer' => $xmailer);
$smtp = Mail::factory('smtp',   array ('host' =>
$host, 'port' =>
$port, 'auth' => true, 'username' =>
$username, 'password' =>
$password));
$mail =
$smtp->send($to,
$headers,
$body);
if (PEAR::isError($mail)) {
echo("<p>" .
$mail->getMessage() . "</p>");  
}
else {   echo("<p>Message successfully sent!</p>");  
}
?>