Friday, May 25, 2012

PHP Send Email

Q. How do I send an email using PHP and Apache webserver under Linux / UNIX operating systems? How do I send email from a PHP Script?

A. The mail() function under PHP allows you to send mail. For the Mail functions to be available, PHP must have access to the sendmail binary on your system during compile time. Usually most webservers are installed with sendmail binary.

Sample PHP Send Email Code

<?php
// Send to?
$to = "vivek@nixcraft.co.in";
 
// The Subject
$subject = "Email Test";
 
// The message
$message = "This is a test.\n
How much is Linux worth today?\n
End of email message!"
;
 
// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70);
 
// Send email
// Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.
// Use if command to display email message status
if ( mail($to, $subject, $message) )
{
echo("Your email message successfully sent.");
}
else
{
echo("Sorry, message delivery failed. Contact webmaster for more info.");
}
?>

Adding Email Headers such as From Email ID

You can add 4th parameters to mail(). This is typically used to add extra headers (From, Cc, and Bcc). Multiple extra headers should be separated with a CRLF (\r\n):
<?php
$to = 'user@example.com';
$subject = 'Test';
$message = 'This is a test.';
// set headers as per your requirements.
$headers = 'From: webmaster@nixcraft.co.in' . "\r\n" .
'Reply-To: webmaster@nixcraft.co.in' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
 
if ( mail($to, $subject, $message, $headers) ) {
echo 'Message sent!';
}
else
{
echo 'Message failed, contact webmaster for more info!';
}
?>

No comments:

Post a Comment