In my previous article, we have discussed about how to send email using SMTP. But in this article we will see how to send mail from form in PHP using simple mail() function.
This process is generally used on website for contact form.
When a visitor open site and want to contact, then he will fill form and admin will get mail of query.
PHP have inbuilt function mail() which is used to send mail. This function contains four argument to send mail which we will see in details below.
Table of Contents
How to Send Emails Using PHP
Parameters are as follows:
to : to whom mail will be sent.
subject: What will be the subject of mail.
message : content or body part of the mail.
from : mail sent from.
Simple contact form to send mail as you can see below:
HTML
<form method="POST"> <div class="form-group"> <input type="name" class="form-control" id="name" placeholder="Name"> </div> <div class="form-group"> <input type="email" class="form-control" id="email" placeholder="Email Address"> </div> <div class="form-group"> <textarea class="form-control" rows="20" placeholder=" Text Here" id="message"></textarea> </div> <input type="submit" class="btn btn-default sub" value="Submit" > </form>
PHP code to send mail as we are using here mail() function. You can see in below given snippet.
PHP
<?php if(isset($_POST['email'])) { extract($_POST); $from=$email; $to="contact@phpcluster.com"; //admin email to contact $subject="Your Subject for mail."; $message= "Name:".$name."\n\r"."Email:".$email."\n\r"."Message:".$message; $emails = mail($to,$subject,$message,"From:".$from); if($emails){ echo "Query Submited Successfully"; } else { echo "Fill Form again"; } } ?>
When a visitor click on submit, then mail will sent to $to value for query. That’s it.
This is the basic approach to send mail in PHP.