How To Send Email In PHP

Sending an email is one of the most basic tasks in web development. Millions of mails are sent to users by the websites everyday.

To send an email in PHP, we use the mail() function. This function has 4 parameters :

  1. to – Email id to which the mail is sent.
  2. subject – The subject of the mail.
  3. headers – The content type of the mail and the email id from which the mail is sent.
  4. message – The actual body or the message of the mail.

The syntax of the mail is mail(to,subject,message,headers).

In the code below, we send an email to the recipient with html body. The html body has the design of a table.
There are two files – index.php, where the user provides his email id and action.php where mail is sent to the user.


<form action="action.php" method="post" enctype="multipart/form-data">

    <label>Email</label> <br>
    <input name="email" type="text" size="30" required /><br><br>

    <input name="submit" type="submit" id="submit" class="submit" value="Submit" />





        $email = $_POST['email'];

        if(filter_var($email, FILTER_VALIDATE_EMAIL) === false || $email=="")
                echo '<h3 style="color:red;">Please enter your email id properly .</h3>';


            // $to is the email id to which the mail is sent
            $to = $email;

            // $subject is the subject
            $subject = "Sample email By Tutsheap";

            //$headers represents the content type and email id from which email is sent
            $headers = "From:\r\n";
            $headers .= "Content-Type: text/html\r\n";

            // $message is the body of the mail
            $message = 'Tutsheap is sharing sample email';

            $message .= <<< EOF
<table rules="all" style="border-color: #666;" cellpadding="10">
<tr style='background: #eee;'><td><strong>Website Name</strong> </td><td></td></tr>
<tr><td><strong>Post:</strong> </td><td> Sending email using PHP</td></tr>
<tr style='background: #eee;'><td><strong>Description</strong> </td><td>Online tutorials library</td></tr>

//EOF represents end of file

            if( mail($to,$subject,$message,$headers) )
                echo '<h3 style="color:green;">Email sent</h3>';




Index Page

Index page

Email Sent Notification

Sent email

Received email

Received email

Email body

Email body

Please feel free to download the source code for reference. In the demo, please wait for some time for receiving email. Also, if you do not receive the mail, then check your spam folder.

View Demo Download source

This content has been helpful to you?

Thanks for contributing!

Yes No