PDA

View Full Version : Using PHP to Send E-mail



Max
September 29th, 2009, 09:40 PM
This is a little tutorial/examples on how to send email using PHP.
PHP makes this very easy.

This will work on both our Windows and Linux servers.

The built-in function that does the job is:

mail(to,subject,message,headers,parameters)

A simple example:

<?php
$to = "[email protected]";
$subject = "Test mail";

//To add a line break in your message use \n
$message = "Hello! This is a simple email message. \n This is line 2 in message \n now we're on line 3";

// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70);


$from = "[email protected]";
$headers = "From: $from";

if(mail($to,$subject,$message,$headers)){
echo "Mail Sent.";
}else{
echo "An error has occurred, mail not sent";
}
?>


To retrieve submitted data from a HTML form using PHP:


<?php
//To assign the text passed from an input field named "message" using the "get" method:
$variable = $_GET['message'];
//For POST Method
$variable2 = $_POST['message'];
?>


More advanced headers can be used if needed, example:

$headers = 'From: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

If you want to send a HTML email, here is an example of one:


<?php
// multiple recipients
$to = '[email protected]' . ', '; // note the comma
$to .= '[email protected]';

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

// message
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
';

// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To: Mary <[email protected]>, Kelly <[email protected]>' . "\r\n";
$headers .= 'From: Birthday Reminder <[email protected]>' . "\r\n";
$headers .= 'Cc: [email protected]' . "\r\n";
$headers .= 'Bcc: [email protected]' . "\r\n";

// Mail it
if(mail($to,$subject,$message,$headers)){
echo "Mail Sent.";
}else{
echo "An error has occurred, mail not sent";
}
?>