Contact Form using PHP

HTML


<form action="" method="post">
<label>Name</label>
<input name="name" type="text" />
<label>Email</label>
<input name="email" type="text" />
<label>Phone</label>
<input name="phone" type="text" />
<label>Message</label>
<textarea name="message"></textarea>
<input name="submit" type="submit" value="Send" />
</form>

Some key things to remember here,

  • action – Action attribute inside the <form> element tell the browser to which page the form is submitted. When left empty the form will be submitted to the current page itself.
  • method – Method can be either POST or GET. It is better to use POST. know more
  • name=’submit’ – This is used in our PHP code to check whether the form is submitted or not.

PHP


<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
if(isset($_POST['submit']))
{
require 'PHPMailer.php';
require 'Exception.php';
$mail = new PHPMailer(true);
try {
$mail->setFrom('info@appunitz.com', 'Appunitz');
$mail->addAddress('deffrin@gmail.com');
$mail->addReplyTo('info@appunitz.com', 'Appunitz');
$mail->addBCC('deffrin@gmail.com'); // Your email address for receiving a copy of the message
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Enquiry Message';
$body = "<label>Name</label><p>".$_POST['name']."</p>".
"<label>Email</label><p>".$_POST['email']."</p>".
"<label>Phone</label><p>".$_POST['phone']."</p>".
"<label>Message</label><p>".$_POST['message']."</p>";
$mail->Body = $body;
$mail->AltBody = $body;
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
}
?>

We are using PHPMailer for sending mail.

$_POST['name'] // variable has the name field's value submitted by the user.

All the working code is available for download.

Download

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *