Sending form data to an email using PHP

In this article, we are going to learn how to collect the form data and send in the mail using PHP.

Gathering form data and deliver to email inbox is a very convenient way and PHP makes this process more dynamic as using this we can handle hundreds of responses per day. This process is based on the client server architecture. The HTML form is on the client side, when user hits the submit button, the data will be sent to the url of the page specified on form action.

Sending form data to an Email

Here, we are going to create two pages - form.php and sendmail.php. The file "form.php" will collect the data you are going to send and the file "sendmail.php" will send the messages.


form.php
<html>
<head>
<title>Sending form data to an Email</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
<div class="wrapper" style="width: 35%; margin: 0 auto;">
<form name="mailinfo" method="post" action="sendmail.php" class="form-signin">
<input type="text" name="to" size="40" class="form-control" placeholder="To:" />
<br/>
<input type="text" name="from" size="40" class="form-control"  placeholder="From:" />
<br/>
<input type="text" name="subject" size="40" class="form-control"  placeholder="Subject:" />
<br/>
<textarea cols="50" rows="5" name="message" class="form-control" placeholder="Enter your message">
</textarea>
<br/><br/>
<input class="btn btn-small btn-primary" type="Submit" value="Send"/>
</form>
</div>	
</body>
</html>

In the above file, we get the inputs from user. When the user click on the send button, "sendmail.php" page is loaded. On this page, we collect all the post data in variables, then we use the PHP mail function to send mail. The mail() function returns a value of 'True' if it is successful and 'False' if it fails.




sendmail.php
<html>
<head>
<title>Sending form data to an Email</title>
</head>
<body>
<?php
$to = $_POST['to'];
$from = $_POST['from'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = 'From: '.$from.'\r\n';
$mailsent = mail($to, $subject, $message, $headers);
if($mailsent) {
echo 'Mail has been sent<br/><br/>';
echo '<b>To: </b>'.$to.'<br/>';
echo '<b>From: </b>'.$from.'<br/>';
echo '<b>Subject: </b>'.$subject.'<br/>';
echo '<b>Message: </b>'.$message.'<br/>';
} else {
echo 'Error in the message.';
}
?>
</body>
</html>	




Related Articles

PHP code to send email using SMTP
Submit a form data without page refresh using PHP, Ajax and Javascript
PHP Server Side Form Validation
Simple pagination in PHP
Simple PHP File Cache
PHP Connection and File Handling on FTP Server
Sending form data to an email using PHP
Recover forgot password using PHP and MySQL






Read more articles


General Knowledge



Learn Popular Language