- Back to Home »
- PHP Tutorial »
- PHP Email
Posted by : senan
Wednesday, February 12, 2014
Welcome! In this section we going to cover how to use the mail function in PHP to send emails.
Download the email examples code on this page
PHP has a built in function mail for sending emails. Using this function we can send plain text emails or HTML emails.
Visit AJAX email script for a working email example code.
PHP Mail Function
mail($to, $subject, $message, $headers);
As you can see above, the mail function has four parameters.
to - the recipients email address
subject - the subject of the email.
message - the email message to be sent.
headers - the header contains information such as the format of the email (plain text or HTML), senders name and email, reply to address, CC and BCC.
Sending Plain Text Email in PHP
The following code will send out a plain text email using the PHP built in mail function.
PHP: Send plain text email
<?php
function send_email($from, $to, $cc, $bcc, $subject, $message){
$headers = "From: ".$from."\r\n";
$headers .= "Reply-To: ".$from."\r\n";
$headers .= "Return-Path: ".$from."\r\n";
$headers .= "CC: ".$cc."\r\n";
$headers .= "BCC: ".$to."\r\n";
if (mail($to,$subject,$message,$headers) ) {
echo "email sent";
} else {
echo "email could not be sent";
}
}
$subject = "Hello!";
$message = "Hello! How are you today?";
send_email("youraddress@domain.com", "recpeient@domain.com",
"someone@domain.com", "hidden_email@domain.com",
$subject ,
$message);
?>
In our send_email function we set the appropriate headers. Reply-To and Return-Path points to the email you want the recipient to reply to. Some server requires the use of Return-Path, so it's good to leave it in there.
Next we call the send_email function which sends out the email.
Sending HTML Email in PHP
The following function will send out an HTML formatted email using the PHP built in mail function.
PHP: Send HTML email
<?php
function send_email($from, $to, $subject, $message){
$headers = "From: ".$from."\r\n";
$headers .= "Reply-To: ".$from."\r\n";
$headers .= "Return-Path: ".$from."\r\n";
$headers .= "Content-type: text/html\r\n";
if (mail($to,$subject,$message,$headers) ) {
echo "email sent";
} else {
echo "email couldn't be sent";
}
}
$subject = "Helloooo!";
$message .= "<html><body>";
$message .= "<b>Hey! How are you today?</b>";
$message .= "<br>Regards";
$message .= "</body></html>";
send_email("youraddress@domain.com", "recpeient@domain.com",
$subject ,
$message);
?>