Email and PHP

PHP has a built in function for sending emails.

mail(to, subject, message, [headers, parameters]);

The first argument is the email address to send to, the second is the subject of the email and the final non-optional argument is the message to send. The headers argument is very useful and will be used in this tutorial.

$to = '';
$subject = 'Subject of Email';
$subject = str_replace(array("\n", "\r"), '', $subject);
$message = 'Message';
$message = wordwrap($message, 70);
$from = '';

These variables set up the to and from address as well as the subject and message.

The subject line cannot contain any new line characters so they have been removed using str_replace.
The message cannot be more than 70 characters in width so wordwrap has been used to wrap them to the correct amount of characters.

$headers = 'From: '.$from." \n\r";
$headers. = 'Reply-To: '.$from."\n\r";

We now make the optional header arguments. We will include the from and reply-to fields. Note that each one must have both end of line characters (\n\r).

if(mail($to, $subject, $message, $headers))
   echo 'Mail sent';

The mail function returns a boolean answer as to whether or not the email was accepted. Note that even if this value returns true it does not guarantee delivery of the email.

The code above was very static, so we will now use a form to allow the to, subject and message to be manually added in a form.

<form id="email" name="email" method="post" action="#">
   <input name="to" id="to" type="text" /><br />
   <input name="subject" id="subject" type="text" /><br />
   <textarea name="message" id="message"></textarea><br />
   <input type="submit" name="submit" id="submit" value="Submit" />

This form has a field for each of the elements we want to have input and a submit button to send the data.

$to = $_POST['to'];
$subject = str_replace(array("\n", "\r"), '', $_POST['subject']);
$message = wordwrap($_POST['message'], 70);

This code is very similar to the first however it gets its values from the form.

We will now use an array of to addresses and loop over them to send the same email to multiple people.

$email = array('Name1' => '','Name2' => '','Name3' => '');
$subject = str_replace(array("\n", "\r"), '', $_POST['subject']);
$message = wordwrap($_POST['message'], 70);
$from = "";
$headers = 'From: '.$from." \n\r";
$headers .= 'Reply-To: '.$from."\n\r";

These variables are the same as those before however we now have an array of email addresses and names. We will now loop over them sending personalised emails to each one.

foreach($email as $name => $address)
   if(mail($address, $subject, 'Dear $name,'.$message, $headers))
      echo 'Mail sent to '.$address;

This loop gets the keys and values from the array and prefixes the message with Dear $name. A message is output for each successful email sent.