Simple send an Email Form script | Learn PHP in 7Days

PHP Send Email Form Script

The below script describes how to send an email using PHP and HTML. In order to understand how this works follow the steps:

  • Create a file named SendEmail.php
  • Copy paste the below code in the same file
  • It is used to display the form to user where he can fill in all the details and hit submit button.
    Code:
    <html> <head> </head>
    <body>
    <form name=”form1″ method=”post” action=”SendEmail.php”>
    <table>
    <tr><td><b>To</b></td><td><input type=”text” name=”mailto” size=”35″></td></tr>
    <tr><td><b>Subject</b></td>
    <td><input type=”text” name=”mailsubject” size=”35″></td></tr>
    <tr><td><b>Message</b></td>
    <td><textarea name=”mailbody” cols=”50″ rows=”7″></textarea></td>
    </tr>
    <tr><td colspan=”2″><input type=”submit” name=”Submit” value=”Send”> </td></tr>
    </table>
    </form>
    </body>
    </html>
  • Next we shall proceed to the PHP code where in it checks, what the user has posted.
  • It receives the user posted data which is stored in the $_POST[“mailsubject”], $_POST[“mailbody”], $_POST[“mailto”].
  • Copy paste the below code in the same file SendEmail.php.
    Code:
    <?phpif($_POST[“submit”])
    { $mailto = $_POST[“mailto”]; $mailsubject = $_POST[“mailsubject”]; $mailbody = $_POST[“mailbody”];//if user left ‘To’ field empty then shows error
    if (empty ($mailto) ) { die ( “Recipient is blank! “) ; }//$mailsubject contains the heading/subject of the email
    if (empty ($mailsubject) ){ $mailsubject=” ” ; }//$mailbody contains the body/content of the email
    if (empty ($mailbody) ) { $mailbody=” ” ;}





    //mail() function is used to send email with the mentioned details
    $result = mail ($mailto, $mailsubject, $mailbody) ;

    //$result is set to on if either email is sent or could not be sent.
    if ($result) { echo “Email sent successfully!” ;}
    else{ echo “Email could not be sent.” ;}
    }
    ?>

  • if user left ‘To’ field empty then we display error
  • $mailsubject contains the heading/subject of the email
  • $mailbody contains the body/content of the email
  • mail() function is used to send email with the mentioned details

 

Few more scripts:

Script to send Mail to multiple recipients

Code:
<?php
$headers = “From:scotutorials@php.com\r\n”;
$recipients = “easyphp@php.com,admin@gmail.com”;
mail($recipients, “This is the subject”,”This is the mail body”, $headers);
?>

Script to send Mail to Multiple recipients in the address field, with commas separating them

Code:
<?php
$mailsend = mail(“receiver1@gmail.com, abcdes@hotmail.com, ajuhgy@aol.com”, “A Sample Subject Line”, “Body of e-mail.”);
print(“$mailsend”);
?>

next