PHP uses a simple function called mail() to send emails. This function requires mainly where to send email (to), the subject of email (subject), the message (message) and from address (from).
A simple Example of PHP Mail Function
1 2 3 4 5 6 7 |
<?php #sendMails.php //to send mail if( mail($to, $subject, $message, $from) ) { echo "Thank you for sending email"; } ?> |
How to send HTML Emails using PHP?
To send HTML emails using mail() function we will need to add a MIME type. Our message header should contain MIME type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<?php #sendMails.php //checking if the contact form has been submitted if(isset($_POST['submit'])) { //storing form data into variables $UName = $_POST['UName']; $UEmail = $_POST['UEmail']; $UMessage = $_POST['UMessage']; $MDate = date('Y-m-d'); $To = "me@cramerz.com"; //validating data (checking all fields have been filled in) if($UName == "" OR $UEmail == "" OR $UMessage == "") { $error = "Please fill all fields to send a message"; } else { //send email to admin $subject = "Contact Us Message!"; $headers = "From:" . $UEmail . " "; $headers .= "Reply-To:" . $UEmail . " "; $headers .= "Return-Path:" . $UEmail . " "; $headers .= "MIME-Version: 1.0 "; $headers .= "Content-Type: text/html; charset=ISO-8859-1 "; $headers .= "bcc:test@cramerz.com"; // BCCs to //$headers .= "CC: sombodyelse@noplace.com "; //formatting message $message = ""; $message .= "<h1>Contact Us Message! </h1><br /> <strong>Date: </strong>" . $MDate . "<br /> <strong>Name: </strong>" . $UName . "<br /> <strong>Email: </strong>" . $UEmail . "<br /> <strong>Message: </strong>" . $UMessage . "." ; $message .= "</body></html>"; //checking if the email has been sent if ( mail($To,$subject,$message,$headers) ) { echo "Email successfully sent"; } else { echo "Could not send email"; } } } ?> |
WHAT IS MIME
MIME stands for Multipurpose Internet Mail Extensions. It is a set of instructions that allows emails to be sent in more than just plain text. Content-Type sets what type of data is going to be sent. The default value would be “text/plain”.
Charset is character set. Each language or set of characters has its own title or name. This value lets the recipient email know which one is used to display the body message.
Click here to read about PHP include().