PHP mail() – send email



PHP mail() function is used for sending emails from your website.

Syntax of mail() function is :

  • mail (to email , Subject of email , email message , header , additional parameters );
  • Here First parameter will be the email address of the receiver
  • Second parameter will be the Subject ( title ) of your email
  • Third parameter will be the content of your email , you can use html tags and all for proper formatting
  • Third parameter is the header of your email, it will contain all the properties and setting for that email , sender email address also should specify in header , we can also add reply to address , format of email etc in header. Using detailed header is a good practice .

Sample of a header
$header = “From: from@gmail.comrnContent-type: text/htmlrnReply-To: from@gmail.com”;

In this header we have specified the from address, reply address and content type of the message.

Now look at a simple example of mail() function

<?php
$from="kssyam@gmail.com";
$to="to@gmail.com";
$subject="Test Mail";
$message="Hi ,<br />".
"This is my test email for learning how to send email using PHP mail function <br />".
"Thank You";
$headers = "From: $fromrnContent-type: text/html";
if(mail($to,$subject, $message, $headers))
{
echo "MAIL SENT SUCCESSFULLY";
}
else
{
echo "SOME ISSUE WITH MAIL SENDING in SERVER";
}
?>

In most of the cases we need to send email from a contact form in our website. Most of the business websites need this functionality , that their user can send and enquiry or messages by filling a contact form in their website.

Now look at a sample PHP program for sending email from a HTML contact form

Consider page contact.html contains the HTML contact form , and mail.php file contains the PHP scripts for sending email.
So contact.html will look like

<form method="post" action="mail.php" name="contact"><br />
Your name :<input type="text" name="username" /><br />
Email :<input type="text" name="useremail" /><br />
Message :<textarea cols="5" rows="5" name="message"></textarea><br />
<input type="submit" value="SEND EMAIL" name="submit" /><br />
</form>

When the user fills the data in form press SUBMIT button , the data is passed to the page mail.php where our mail(0 function is there . Now look at the code in mail.php

<?php
$username=$_POST['username'];
$from=$_POST['useremail'];
$to="to@gmail.com";
$subject="New Enquiry from ".$username;
$message=$_POST['message'];
$headers = "From: $fromrnContent-type: text/html";
if(mail($to,$subject, $message, $headers))
{
echo "MAIL SENT SUCCESSFULLY";
}
else
{
echo "SOME ISSUE WITH MAIL SENDING in SERVER";
}
?>

In this case, when a user submit the data an email will sent to “to@gmail.com” with a subject like “New Enquiry from JOHN” and content which is typed by the user in form.

This is only a basic introduction tutorial about mail function in PHP. In our later posts we will learn to send attachments and other advanced headers along with email.