How to use PHP mail to send emails from your website
The following article explains how to use PHP mail to send emails. PHP mail makes use of the mail() function and sends the email based on the parameters specified. Send a Simple Email Message
Below is a sample script for PHP mail:
<?php
$to = 'user@domain.com';
$subject = 'the subject';
$from = 'email@domain.com';
$message = 'hello';
if(mail($to, $subject, $message, "From: $from"))
echo "Mail sent";
else
echo "Mail send failure - message not sent"; ?>
$to = 'user@domain.com';
$subject = 'the subject';
$from = 'email@domain.com';
$message = 'hello';
if(mail($to, $subject, $message, "From: $from"))
echo "Mail sent";
else
echo "Mail send failure - message not sent"; ?>
Email the Results of a Form
To send the results of a form as an email from your website you will need to first create the HTML form. Within the form you will need to set the action to the page containing your PHP mail code. For example:
<form action="phpmailform.php" method="post">
Next, you will need to create the PHP page specified in the action which will contain the PHP mail code.
Below is a sample script you can use for PHP mail:
<?php
$to = 'user@domain.com';
$subject = 'the subject';
$from = 'email@domain.com';
$message ='';
foreach($_POST as $name => $data)
{
if(is_array($data))
{
foreach($data as $datum)
$message .= $name . ": " . $datum . " \n";
}
else
$message .= $name . ": " . $data . " \n";
}
# Attempt to send email
if(mail($to, $subject, $message, "From: $from"))
echo "Mail sent";
else
echo "Mail send failure - message not sent";
?>
Sending HTML Emails$to = 'user@domain.com';
$subject = 'the subject';
$from = 'email@domain.com';
$message ='';
foreach($_POST as $name => $data)
{
if(is_array($data))
{
foreach($data as $datum)
$message .= $name . ": " . $datum . " \n";
}
else
$message .= $name . ": " . $data . " \n";
}
# Attempt to send email
if(mail($to, $subject, $message, "From: $from"))
echo "Mail sent";
else
echo "Mail send failure - message not sent";
?>
To send the body of the email as HTML include the follow lines of code:
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
Replace the Attempt to send email section with the following:
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
# Attempt to send email
if(mail($to, $subject, $message, "$headers \r\n From: $from"))
echo "Mail sent";
else
echo "Mail send failure - message not sent";
if(mail($to, $subject, $message, "$headers \r\n From: $from"))
echo "Mail sent";
else
echo "Mail send failure - message not sent";

There are no comments for this entry.
[Add Comment]