Sending of an Email is most required feature of any Website for connect user to system, so in this post we have discuss how can we send email on form submission by using PHP script with PHPMailer Library class. PHPMailer class is an other alternative of PHP mail() function to send an Email by using SMTP settings. If you have an Email hosting account then you can use this PHPMailer class for send an email from your website by provide SMTP credential.
In this post we have learn how can we send email from localhost in PHP script by using PHPMailer. If you have use PHP mail() function for send an email then you have to set Email configuration in your php.ini file but if you have use PHPMailer class then you can use any Email hosting account for send an email on form submission or any event in your website as you set.
Here we will learn how to use PHPMailer in PHP and how can we configure into our PHP script or form submission event. For use this class we have required SMTP username and password and we also know SMTP host server name also. If you do not know, so please collect this information first for use this class, without knowing this information we can not configured PHPMailer class into our web application. If we have successfully configured SMTP settings then we can send Email via SMTP server in PHP using PHPMailer. In this post we have make simple contact form for user to send his or her feedback to owner of website via Email send using PHPMailer.
Source Code
index.php
<?php
//index.php
$error = '';
$name = '';
$email = '';
$subject = '';
$message = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
}
else
{
$name = clean_text($_POST["name"]);
if(!preg_match("/^[a-zA-Z ]*$/",$name))
{
$error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
}
}
if(empty($_POST["email"]))
{
$error .= '<p><label class="text-danger">Please Enter your Email</label></p>';
}
else
{
$email = clean_text($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error .= '<p><label class="text-danger">Invalid email format</label></p>';
}
}
if(empty($_POST["subject"]))
{
$error .= '<p><label class="text-danger">Subject is required</label></p>';
}
else
{
$subject = clean_text($_POST["subject"]);
}
if(empty($_POST["message"]))
{
$error .= '<p><label class="text-danger">Message is required</label></p>';
}
else
{
$message = clean_text($_POST["message"]);
}
if($error == '')
{
require 'class/class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); //Sets Mailer to send message using SMTP
$mail->Host = 'smtpout.secureserver.net'; //Sets the SMTP hosts
$mail->Port = '80'; //Sets the default SMTP server port
$mail->SMTPAuth = true; //Sets SMTP authentication. Utilizes the Username and Password variables
$mail->Username = 'xxxxxxxxxx'; //Sets SMTP username
$mail->Password = 'xxxxxxxxxx'; //Sets SMTP password
$mail->SMTPSecure = ''; //Sets connection prefix. Options are "", "ssl" or "tls"
$mail->From = $_POST["email"]; //Sets the From email address for the message
$mail->FromName = $_POST["name"]; //Sets the From name of the message
$mail->AddAddress('info@find2rent.com', 'Name');//Adds a "To" address
$mail->AddCC($_POST["email"], $_POST["name"]); //Adds a "Cc" address
$mail->WordWrap = 50; //Sets word wrapping on the body of the message to a given number of characters
$mail->IsHTML(true); //Sets message type to HTML
$mail->Subject = $_POST["subject"]; //Sets the Subject of the message
$mail->Body = $_POST["message"]; //An HTML or plain text message body
if($mail->Send()) //Send an Email. Return true on success or false on error
{
$error = '<label class="text-success">Thank you for contacting us</label>';
}
else
{
$error = '<label class="text-danger">There is an Error</label>';
}
$name = '';
$email = '';
$subject = '';
$message = '';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Send an Email on Form Submission using PHP with PHPMailer</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<div class="row">
<div class="col-md-8" style="margin:0 auto; float:none;">
<h3 align="center">Send an Email on Form Submission using PHP with PHPMailer</h3>
<br />
<?php echo $error; ?>
<form method="post">
<div class="form-group">
<label>Enter Name</label>
<input type="text" name="name" placeholder="Enter Name" class="form-control" value="<?php echo $name; ?>" />
</div>
<div class="form-group">
<label>Enter Email</label>
<input type="text" name="email" class="form-control" placeholder="Enter Email" value="<?php echo $email; ?>" />
</div>
<div class="form-group">
<label>Enter Subject</label>
<input type="text" name="subject" class="form-control" placeholder="Enter Subject" value="<?php echo $subject; ?>" />
</div>
<div class="form-group">
<label>Enter Message</label>
<textarea name="message" class="form-control" placeholder="Enter Message"><?php echo $message; ?></textarea>
</div>
<div class="form-group" align="center">
<input type="submit" name="submit" value="Submit" class="btn btn-info" />
</div>
</form>
</div>
</div>
</div>
</body>
</html>
awesome video sir thanks for posting source code... keep going sir
ReplyDeleteMost of your codes did not work.you may change codes before uploading..i tried your almost all codes tuts.but they did not working...same this..no error not response..
ReplyDeleteThank you weblesson for being generous and not stingy in sharing your knowledge in programming especially in PHP PDO AJAX JQuery. I hope you teach us also in making a system like Library System that is also in PHP PDO AJAX JQuery using Function Call. Like this one:
ReplyDeletefunction Login()
{
if(empty($_POST['username']))
{
$this->HandleError("Username is empty!");
return false;
}
if(empty($_POST['password']))
{
$this->HandleError("Password is empty!");
return false;
}
}
Please.... Thank you in advance. God bless. More power to you website and your company. :)
Hi, again. I have another request. Please create or make a PHP PDO AJAX JQquery for this. Please, please, please.... Thanks and God bless. :)
ReplyDeletehttps://www.sourcecodester.com/tutorials/php/9202/validating-and-saving-new-member-advance-php.html
getFieldsOnOneTable(self::$tbl_name);
}
function listOfautonumber(){
global $mydb;
$mydb->setQuery("Select * from ".self::$tbl_name);
$cur = $mydb->loadResultList();
return $cur;
}
static function bPrimary($id=0){
global $mydb;
$mydb->setQuery("SELECT * FROM ".self::$tbl_name." WHERE auto_id={$id} LIMIT 1");
$row = $mydb->loadSingleResult();
$s = $row->autostart + $row->incval;
$a = $row->appenchar;
return $a.$s;
}
static function bPrimaryUpdate($id=0){
global $mydb;
$mydb->setQuery("SELECT * FROM ".self::$tbl_name." WHERE auto_id={$id} LIMIT 1");
$row = $mydb->loadSingleResult();
$s = $row->autostart + $row->incval;
return $s;
}
/*---Instantiation of Object dynamically---*/
static function instantiate($record) {
$object = new self;
foreach($record as $attribute=>$value){
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
/*--Cleaning the raw data before submitting to Database--*/
private function has_attribute($attribute) {
// We don't care about the value, we just want to know if the key exists
// Will return true or false
return array_key_exists($attribute, $this->attributes());
}
protected function attributes() {
// return an array of attribute names and their values
global $mydb;
$attributes = array();
foreach($this->db_fields() as $field) {
if(property_exists($this, $field)) {
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
protected function sanitized_attributes() {
global $mydb;
$clean_attributes = array();
// sanitize the values before submitting
// Note: does not alter the actual value of each attribute
foreach($this->attributes() as $key => $value){
$clean_attributes[$key] = $mydb->escape_value($value);
}
return $clean_attributes;
}
/*--Create,Update and Delete methods--*/
public function save() {
// A new record won't have an id yet.
return isset($this->id) ? $this->update() : $this->create();
}
public function create() {
global $mydb;
// Don't forget your SQL syntax and good habits:
// - INSERT INTO table (key, key) VALUES ('value', 'value')
// - single-quotes around all values
// - escape all values to prevent SQL injection
$attributes = $this->sanitized_attributes();
$sql = "INSERT INTO ".self::$tbl_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES ('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
echo $mydb->setQuery($sql);
if($mydb->executeQuery()) {
$this->id = $mydb->insert_id();
return true;
} else {
return false;
}
}
public function update($id=0) {
global $mydb;
$attributes = $this->sanitized_attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE ".self::$tbl_name." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE auto_id=". $id;
$mydb->setQuery($sql);
if(!$mydb->executeQuery()) return false;
}
public function delete($id=0) {
global $mydb;
$sql = "DELETE FROM ".self::$tbl_name;
$sql .= " WHERE auto_id=". $id;
$sql .= " LIMIT 1 ";
$mydb->setQuery($sql);
if(!$mydb->executeQuery()) return false;
}
}
?>
Coz I like so much this code... Please, please, please...
Sorry for flooding.
There is an Error. why ?
ReplyDeleteHey Admin. Hope you don't mind what I'm telling you. Your given source code has a bug. Please fix that bug.
ReplyDeleteAnd this is the Bug. When I register in your given Send an Email on Form.
I've got this.
Warning: fwrite() expects parameter 1 to be resource, integer given in C:\xampp\htdocs\email-address-verification\class\class.smtp.php on line 1023
Please fix that Admin.
fwrite(): send of 16 bytes failed with errno=32 Broken pipe in /opt/lampp/htdocs/send-an-email/class/class.smtp.php on line 1023 how can sovle this problem and my code
ReplyDelete$mail->Host = 'smtp.gmail.com';
$mail->Port = '465';
I've faced same problem, have you find any solutions lately?
Deleteplease send me complete book an appointment form with dates and time
ReplyDeleteim try in localhost,
ReplyDeleteCant send mail,
Help me..
email is not working
ReplyDeleteGiving this error
ReplyDeleteThere is an Error
I have a problem.. I can't send to my gmail. show 'There is erro'
ReplyDeletewhy, please.
escribeme a inioris1@gmail.com para explicarte
DeleteSame issue can't send it to my gmail :/
ReplyDeleteCould you please tell me how can we find the path of 'class/class.phpmailer.php'
ReplyDeleteSir , Error is coming in the same code while running... There is an error.. How to resolve this error
ReplyDeleteSir , Error is coming in the same code while running... There is an error.. How to resolve this error
ReplyDeletethere is error plz rectify the code
ReplyDeleteIt works perfectly, as usual thanks man
ReplyDeleteError sir
ReplyDeleteFatal error: Uncaught Error: Call to undefined function IsSMTP() in D:\xampp\htdocs\oswego-rental-properties\contactus.php:68 Stack trace: #0 {main} thrown in D:\xampp\htdocs\oswego-rental-properties\contactus.php on line 68
ReplyDeleteSir, please help me How to solve this
wkwkw error, can not be continued
ReplyDeletewhat is smpt username and password
ReplyDeletewhat is SMTP username and password
ReplyDeletehello, can we have the some video on laravel
ReplyDeleteerrroneous
ReplyDeleteShowing "There is an Error" Cant find where is the issue
ReplyDeleteThere is an Error
ReplyDeletePlease provide a link to download a phpmailer required class.
ReplyDeletewithout it it's not possible to send mail only using php.
Please provide the class file for mailing.
ReplyDeleteworks perfectly well. thanks a million <3
ReplyDeleteIt works :) Thank you!
ReplyDeletemy error is SMTP Connect() failed.
ReplyDeletepls help me!
working great
ReplyDeletehow did they fixed it
Deleteit works great, for all that people are saying it doesn't work, it's necessary download the PHPMailer library, curently we have to change like 3 lines because the library has some changes nowadays, but this example is so helpful
ReplyDeleteworks Perfectly ...
ReplyDelete1.Download PhpMailer Module
2.can also use require_once('PhpMailer/PHPMailerAutoload.php'); instead of require 'PhpMailer/class.phpmailer.php';
3.Set your username and password correctly.