How to Send an Email in PHP

Leave a Comment

To send an email in PHP, use PHP’s built-in mail() function.
mail ( string to, string subject, string message [, string additional_headers [, string
additional_parameters]])

You'll notice from the return type of the function that a Boolean is returned upon completion. If PHP successfully passed the email to the SMTP server then true is returned. If an error occurred then false is returned. Please note that even if true is returned the mail may not be sent! (For example if the SMTP is incorrectly configured. In this case you should consult your SMTP server logs to see what went wrong).

To send the email from the previous section - with error checking - we use the following code:
<?php
$to = "Mary@xyz.com";
$from = "jsss@www.com";
$subject = "This is a test email";
$message = "Dear Mary,\n\n\n This is just a test email.\n\n From Chris.";
$headers = "From: $from\r\n";
$success = mail($to, $subject, $message, $headers);
if ($success)
echo "The email to $to from $from was successfully sent";
else
echo "An error occurred when sending the email to $to from $from";
?>

It is also possible to send an email to multiple recipients with a single call to the mail() function. Here is an example. All you need to do is modify the recipient variable as follows:
<?php
$to = " Mary@xyz.com, def@wer.com";
?>

0 comments:

Post a Comment