Send email with PHP with headers


Against contrary belief it's fairly easy to send emails using PHP. In just afew lines of code you can set up an email.

All we need is the right configuration in PHP (emailserver localhost,etc) and the mail() function to send our first email.

In the first argument we specify the recipient in our example :
$to = "recipient@example.com";

Next we create the title we want to send through the email function.
$subject = "Hi!";

Finaly we add the message argument. Use \n as breaks.
$body = "Hi,\n\nHow are you?";


Watch the full PHP code example :
<?php
$to = "recipient@example.com";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";
if (mail($to, $subject, $body)) {
	echo "

Message successfully sent!

"; } else { echo "

Message delivery failed...

"; } ?>


The PHP configuration specifies a standard sender address.
We can customize this by sending additional header with our email function.
$header = "From: sender@domain.com\r\n";
$header .= "Reply-To: sender@domain.com\r\n";
$header .= "Return-Path: sender@domain.com\r\n";
All we have to do to attach our headers to the email is write the following code :
mail($to, $subject, $body, $header);




Posted by James on 2009-08-06 in the category " php "