Sending e-mails with PHP

How to send e-mails using the PHP function mail(); and tips to ensure it works. (July 27, 2009)

 

Here is the basic example to send an e-mail using PHP:
<?php
// Sample from www.josepino.com

// Replace with your e-mail address
$email = "name@server.com";

// Write the subject
$subject = "Here goes the Subject.";

// Remember to break the message with \r\n
$message  = "Here goes the content of the e-mail\r\n";
$message .= "Write as much you want but don't forget to \r\n";
$message .= "break the lines with carriage return and \r\n";
$message .= "new line escape codes.\r\n";

mail($email, $subject, $message, "From: $email");

echo "Done.";

?>

 

If you get an error or if the e-mail simply doesn't go anywhere, you may need to define the e-mail address as 'sendmail_from' using the function ini_set();. Set the souce before using the mail(); function.

 

Here is the example:
<?php

// Sample from www.josepino.com
// define headers, email address, subject and message

$message = "Write the message here";
$to      = "name@server.com";
$from    = "source@server.com";
$headers = "From: " . $from;
$subject = "Write the subject here.";

ini_set(sendmail_from, $from);

mail($to, $subject, $message, $headers);
?>
Now, we can check if the server was able to send the e-mail. As the mail(); function provides a boolean result, it can be tested with if():
<?php

// Sample from www.josepino.com
// Display an error if the server can't send the e-mail

$message = "Write the message here";
$to      = "name@server.com";
$from    = "source@server.com";
$headers = "From: " . $from;
$subject = "Write the subject here.";

ini_set(sendmail_from, $from);

if (mail($to, $subject, $message, $headers)) {
   echo "Your message was sent";
} else {
   echo "There was an error when trying to send the message";
}
?>
You can also define the 'Reply to' address, 'cc' and 'bcc':
<?php

// Sample from www.josepino.com
// define Reply-to address, cc and bcc when sending
// emails with PHP

$message  = "Write the message here";
$to       = "name@server.com";
$from     = "source@server.com";
$headers  = "From: " . $from;
$headers .= "\r\nReply-To: return@email.com\r\n";
$headers .= "Cc: copy@address.com\r\n";
$headers .= "Bcc: hidden@contact.com\r\n";
$subject  = "Write the subject here.";

ini_set(sendmail_from, $from);

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

 

I Hope it helps.

 


 < Reverse Sort Arrays With PHPHomepage
php Index
 

 

If any information, data, picture or design infringes a copyrighted material, please send me an e-mail asking to remove it along with the supporting data.
Some features may not work with Google Chrome. © 2006-2010 Jose Pino - Powered by JPC Alpha