Friday, December 20, 2013

Sending Email through PHP

Sending email though PHP is very easy using the PHP function mail(). But we have to append the email headers for adding options like adding CC (carbon copy) and BCC (Behind Carbon Copy). The following is the code to send Email with different options.

<?php 
//Message to be send
$message = "Hi, This is a sample mail send through PHP using additional headers .";
//Subject of the message
$subject = "Test mail";

//Adding from email ID. This is required.
$headers = "From: $from\r\n";

//If the email has HTML content the following lines needs to be added to header. This is optional.
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

//If the email has different reply to email other than the from email ID.  This is optional.
$headers .= "Reply-To: $replyto\r\n";

//To send a CC of this email to another email ID. This is optional. If we want to send CC to more than one email ID, we have to add multiple email ids separated by after Cc:
$headers .= "Cc: $cc_mailid \r\n";

//To send a BCC of this email to another email ID. This is optional. If we want to send BCC to more than one email ID, we have to add multiple email ids separated by after Bcc:
$headers .= "Bcc: $bcc_mailid \r\n";

//Finally, to the send the email with the above options.
If  (mail($to, $subject, $message, $headers)
                echo "Email send successfully.";
else
                echo "There was an error while send the email.";
?>

Note: The above program will only work if your server is properly configured for e-mail.  Therefore this program may not work in your local installation. Some web servers may have the email server hosted on another machine.


No comments :

Post a Comment