Contact us form with PHPMailer and ReCaptcha V2 - php

I want to use the below contact us form; I tested it, and I sent emails. There are few issues that I am unable to sort out so that I use the form on a development site. The issues are:
When the user hits send an email button while the form is empty, he does not get an alert that the ReCaptcha field is required.
If you fill the form and completely ignore the ReCaptcha and hit the send button, you will be taken to a white page, and the email will not be sent. Obviously, this is an error that is not communicated properly to the user.
If you fill the form properly and hit send, the thank you page's code does not capture your message. I tried using both GET and Post. For example: <?php echo $_POST["name"]?> and <?php echo $_GET["name"]?>.
I use PHP version 8.0.3.
I appreciate it if someone can help me solve these issues.
Index.php
<!DOCTYPE HTML>
<html>
<head>
<title>Test form to email</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<div class ="container">
<div class="col-lg-6 push-lg-3">
<h1> Contact us</h1>
<p>Fill out the below form to contact us</p>
<form id= "contactus" method= "post" action= "send.php">
<input type= "text" name = "name" class = "form-control" placeholder="your Name" required><br />
<input type= "tel" name = "phone" class = "form-control" placeholder="your Phone" required><br />
<input type= "email" name = "email" class = "form-control" placeholder="your email address" required><br />
<textarea name="message" placeholder="your Message" class = "form-control" required></textarea><br />
<div class="g-recaptcha" data-sitekey="ENTER_YOUR_SITE_KEY_HERE"></div><br />
<button type= "submit" class = "btn btn-success">Send email</button>
</form>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous"></script>
<script src="./js/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script>
$("#contactus").validate();
</script>
</body>
</html>
send.php
<?php
/**
* Contact us form for PHPMailer and ReCaptcha V2.
* Built based on the following resources
* https://www.youtube.com/watch?v=3o0WXaXfUwI
* https://stackoverflow.com/questions/50253428/verify-recaptcha-v2-always-false
* This code is not yet final and requires refinement and help from the great community of stackoverflow.com
*/
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php'; //confirm this path
require 'vendor/phpmailer/phpmailer/src/SMTP.php'; //confirm this path
require 'vendor/phpmailer/phpmailer/src/Exception.php'; //confirm this path
//get the variables from the form
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
//validations
if(empty($name)){
header("location:index.php?nouser");
exit();
}
if(empty($phone)){
header("location:index.php?nophone");
exit();
}
if(empty($email)){
header("location:index.php?noemail");
exit();
}
if(empty($message)){
header("location:index.php?nomessage");
exit();
}
//PHPMailer desfault validations
//Apply some basic validation and filtering to the email
if (array_key_exists('email', $_POST)) {
$email = substr(strip_tags($_POST['email']), 0, 255);
} else {
$email = 'No email';
}
//Apply some basic validation and filtering to the message
if (array_key_exists('message', $_POST)) {
//Limit length and strip HTML tags
$message = substr(strip_tags($_POST['message']), 0, 16384);
} else {
$message = '';
$msg = 'No message provided!';
$err = true;
}
//Apply some basic validation and filtering to the name
if (array_key_exists('name', $_POST)) {
//Limit length and strip HTML tags
$name = substr(strip_tags($_POST['name']), 0, 255);
} else {
$name = '';
}
//Load Composer's autoloader
require 'vendor/autoload.php'; //confirm this path
$response = isset($_POST["g-recaptcha-response"]) ? $_POST['g-recaptcha-response'] : null;
$privatekey = "ENTER_YOUR_PRIVATE_KEY"; //Enter your secret key here
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'secret' => $privatekey,
'response' => $response,
'remoteip' => $_SERVER['REMOTE_ADDR']
));
$resp = json_decode(curl_exec($ch));
curl_close($ch);
if ($resp->success) {
//Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 0; //Enable verbose debug output
$mail->isSMTP(); //Send using SMTP
$mail->Host = 'mail.example.com'; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = 'support#example.com'; //SMTP username
$mail->Password = 'PASSWORD'; //SMTP password
$mail->SMTPSecure = 'tls'; //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587; //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Sender
$mail->setFrom('sender#example.com', 'Mr.sender');
//Recipients
$mail->addAddress('recipient#example.com', 'Mr. Recipient'); //Add a recipient
//Body content
$body = "<p><strong>Hello</strong>, you have received an inquiry from " . $name . " the message is " . $message . " you can contact the sender by phone on " . $phone . " or by email on " . $email . "</p>";
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'Website inquiry from ' . $name;
$mail->email = 'The sender email ' . $email;
$mail->Body = $body;
$mail->AltBody = strip_tags($body);
$mail->send();
//echo 'Message has been sent'; // select this if you want to echo that the message has been snet
header("location: thankyou.php"); // Select this if you want to redirect to a thank you page
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}
?>
thankyou.php
<!DOCTYPE HTML>
<html>
<head>
<title>Thank you <?php echo $_GET['name'];?> </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container mt-5 text-center">
<body>
<h1>Thank You <?php echo $_GET['name'];?></h1>
<p>We have received your inquiry. Here is the information you have submitted:</p>
<ol>
<li><em>Name:</em> <?php echo $_GET["name"]?></li>
<li><em>Email:</em> <?php echo $_GET["email"]?></li>
<li><em>Phone:</em> <?php echo $_GET["phone"]?></li>
<li><em>Message:</em> <?php echo $_GET["message"]?></li>
</ol>
</body>
</div>
</body>
</html>

Related

Why mail was sending without confirm the form or don't sending at all and get Timeout?

I have a very interesting problem with my script. I need to send a brief to my email, and I use PHP Mailer for that.
<?php
use PHPMailer\PHPMailer\PHPMailer;
require 'vendor/autoload.php';
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'mail.webtests.xyz';
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->Username = 'yapik#webtests.xyz';
$mail->Password = '1104Romik!';
$mail->setFrom('yapik#webtests.xyz', 'Yaroslav Kretov');
$mail->addAddress($_POST['email'], $_POST['name']);
if ($mail->addReplyTo($_POST['email'], $_POST['name'])) {
$mail->Subject = 'PHPMailer contact form';
$mail->isHTML(false);
$mail->Body = <<<EOT
Email: {$_POST['email']}
Name: {$_POST['name']}
Message: {$_POST['message']}
EOT;
if (!$mail->send()) {
$msg = 'Sorry, something went wrong. Please try again later.';
} else {
$msg = 'Message sent! Thanks for contacting us.';
}
} else {
$msg = 'Share it with us!';
}
}
else{
echo 'error';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact form</title>
</head>
<body>
<h1>Do You Have Anything in Mind?</h1>
<?php if (!empty($msg)) {
echo "<h2>$msg</h2>";
} ?>
<form method="POST">
<label for="name">Name: <input type="text" name="name" id="name"></label><br><br>
<label for="email">Email: <input type="email" name="email" id="email"></label><br><br>
<label for="message">Message: <textarea name="message" id="message" rows="8" cols="20"></textarea></label><br><br>
<input type="submit" value="Send">
</form>
</body>
</html>
It sends a brief but before I confirm this form, or don't send it at all and give me timeout. I don't know what I should do.

PHPmailer fuction only will receive from one email

I have searched for this answer for the past few days and have tried everything to make this work so please help.
I had made a contact form but I will only receive an email if I use the email that the form is submitting to. If I use any other email it will still said the email is sent but when I check my inbox there is nothing there. Same as my junk and sent folders. Although if I complete the form with my email I will get an email in my inbox. (So the form email and the email address submitting to is the same).
This is my index.php
<!DOCTYPE html>
<html>
<head>
<title>Send an Email</title>
</head>
<body>
<center>
<h4 class="sent-notification"></h4>
<form id="myForm">
<h2>Send an Email</h2>
<label>Name</label>
<input id="name" type="text" placeholder="Enter Name">
<br><br>
<label>Email</label>
<input id="email" type="text" placeholder="Enter Email">
<br><br>
<label>Subject</label>
<input id="subject" type="text" placeholder=" Enter Subject">
<br><br>
<p>Message</p>
<textarea id="body" rows="5" placeholder="Type Message"></textarea>
<br><br>
<button type="button" onclick="sendEmail()" value="Send An Email">Submit</button>
</form>
</center>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function sendEmail() {
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
body: body.val()
}, success: function (response) {
$('#myForm')[0].reset();
$('.sent-notification').text("Message Sent Successfully.");
}
});
}
}
This is my sendEmail.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
if(isset($_POST['name']) && isset($_POST['email'])){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$body = $_POST['body'];
require 'vendor/autoload.php';
$mail = new PHPMailer();
//Server settings
$mail->isSMTP(); //Send using SMTP
$mail->Host = 'smtp.mail.yahoo.com'; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = 'atouchof.beauty#yahoo.com'; //SMTP username
$mail->Password = 'aaa'; //SMTP password
$mail->SMTPSecure = 'tsl'; //Enable implicit TLS encryption
$mail->Port = 587; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
$mail->isHTML(true); //Set email format to HTML
$mail->setFrom($email, $name);
$mail->addAddress("atouchof.beauty#yahoo.com");
$mail->Subject = ("$email ($subject)");
$mail->Body = $body;
if($mail->send()){
$status = "success";
$response = "Email is sent!";
}
else
{
$status = "failed";
$response = "Something is wrong: <br>" . $mail->ErrorInfo;
}
exit(json_encode(array("status" => $status, "response" => $response)));
}
?>
This may sound confusing so please ask any questions if you don't understand.
Two problems. Firstly you're forging the from address, which is very probably the cause of your problems. This is well documented, and I recommend following the advice given in the PHPMailer contact form example.
A minor issue is that you're setting this to a non-existent value:
$mail->SMTPSecure = 'tsl';
That should be:
$mail->SMTPSecure = 'tls';
You can call multiple times:
$mail->AddAddress('emailONE#gmail.com', 'Juan');
$mail->AddAddress('emailTWO#gmail.com', 'Pepe');
I recommend use https://mailtrap.io/ for testing emails

PHPMailer form sends after correct email without stopping to check fields that are still empty [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to develop a contact form using PHPMailer and validating with server-side for the purpose of this question. (javascript validation will be done later).
so I have added the post variables with sanitization and validate empty fields for each field in order.
It validates successfully for the name entered and the email when it is entered correctly, but when I press submit to test the subject and message fields if they are empty, it sends the form before it ever validates the subject and the message fields.
Somehow when it throws the catch exception for the email when it is successful, it sends the form while disregarding the rest of the form.
I am following tutorials, but I dont have solid answers as to why this is happening in my case.
Any ideas will be great help.
P.S. the hidden phone input field is for honeypot.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="content">
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use phpmailer\phpmailer\PHPMailer;
use phpmailer\phpmailer\SMTP;
use phpmailer\phpmailer\Exception;
require 'phpmailer/Exception.php';
require 'phpmailer/PHPMailer.php';
require 'phpmailer/SMTP.php';
if (empty($_POST['phone'])) {
if (isset($_POST['sendmail'])) {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if (empty($name)) {
echo '<p class="error">Please enter your name</p>';
}
if (empty($email)) {
echo '<p class="error">Please enter your email</p>';
}
if (empty($subject)) {
echo '<p class="error">Please enter your subject</p>';
}
if (empty($message)) {
echo '<p class="error">Please enter your message</p>';
}
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
//$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.gmail.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'email'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('email', 'Custom Form');
$mail->addAddress($email, $name); // Add a recipient
$mail->addReplyTo('email');
// Attachments
//$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
// body content
$body = "<p>Enquiry from: " . ucwords($name) . "<br> Message: " . $message . "</p>";
// Content
$mail->isHTML(true);
$mail->Name = 'Website enquiry from:' . $name; // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AltBody = strip_tags($body);
$mail->send();
echo '<p class="success">Your message has been sent!</p>';
} catch (Exception $e) {
echo "<p class='error'>Message could not be sent. <br> Mailer Error: {$mail->ErrorInfo}</p>";
}
}
}
?>
<!-- <p class="success">Your message has been sent!</p>
<p class="error">Message could not be sent. Mailer Error: </p> -->
<form role="form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<input type="text" id="name" name="name" placeholder="Enter your name">
<input type="email" id="email" name="email" placeholder="Enter your email">
<input type="text" id="subject" name="subject" placeholder="Enter subject line" maxlength="50">
<textarea type="textarea" id="message" name="message" placeholder="Your Message Here" maxlength="6000" rows="4">Test mail using PHPMailer</textarea>
<input type="hidden" name="phone">
<button type="submit" name="sendmail">Send</button>
</form>
</div>
I quickly rattled through the above and re-factored it slightly so that errors found during processing are recorded to an errors array - the mail will not be sent if this array is not empty. this remains untested but I hope will illustrate a possible method to adopt for ensuring the user has supplied the necessary data
<?php
$errors=array();
$status=false;
if( $_SERVER['REQUEST_METHOD']=='POST' && empty( $_POST['phone'] ) ) {
if( isset(
$_POST['sendmail'],
$_POST['name'],
$_POST['email'],
$_POST['subject'],
$_POST['message']
) ) {
$args=array(
'name' => FILTER_SANITIZE_STRING,
'email' => FILTER_SANITIZE_EMAIL,
'subject' => FILTER_SANITIZE_STRING,
'message' => FILTER_SANITIZE_STRING
);
$_POST=filter_input_array( INPUT_POST, $args );
extract( $_POST );
$email=filter_var( $email, FILTER_VALIDATE_EMAIL );
if( empty( $name ) )$errors[]='Please enter your name';
if( empty( $email ) )$errors[]='Please enter a valid email address';
if( empty( $subject ) )$errors[]='Please enter your subject';
if( empty( $message ) )$errors[]='Please enter your message';
if( empty( $errors ) ){
use phpmailer\phpmailer\PHPMailer;
use phpmailer\phpmailer\SMTP;
use phpmailer\phpmailer\Exception;
require 'phpmailer/Exception.php';
require 'phpmailer/PHPMailer.php';
require 'phpmailer/SMTP.php';
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
//$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.gmail.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'email'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('email', 'Custom Form');
$mail->addAddress($email, $name); // Add a recipient
$mail->addReplyTo('email');
// body content
$body = "<p>Enquiry from: " . ucwords($name) . "<br> Message: " . $message . "</p>";
// Content
$mail->isHTML(true);
$mail->Name = 'Website enquiry from:' . $name; // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AltBody = strip_tags($body);
$status=$mail->send();
} catch (Exception $e) {
$errors[]="<p class='error'>Message could not be sent. <br> Mailer Error: {$mail->ErrorInfo}</p>";
}
}
}
}
?>
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="content">
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if( !empty( $errors ) ){
foreach( $errors as $error )printf('<p class="error">%s</p>', $error );
}
if( $status ){
echo '<p class="success">Your message has been sent!</p>';
}
}
?>
<form role="form" method="post">
<input type="text" id="name" name="name" placeholder="Enter your name">
<input type="email" id="email" name="email" placeholder="Enter your email">
<input type="text" id="subject" name="subject" placeholder="Enter subject line" maxlength="50">
<textarea id="message" name="message" placeholder="Your Message Here" maxlength="6000" rows="4">Test mail using PHPMailer</textarea>
<input type="hidden" name="phone">
<button type="submit" name="sendmail">Send</button>
</form>
</div>
</body>
</html>

PHP contact form not getting all information from another php file

I created a simple contact form where variable $result output is not appearing above that form when the form is submitted. Please help me out.This contact form works fine in the same php file but when I try with another php file(in my case,fetch.php),variable $result in h4 tag of index.php shows no output after submitting form.
index.php
<?php
include 'fetch.php';
?>
<!DOCTYPE html>
<!-- -->
<html>
<head>
<meta charset="UTF-8">
<title>PHPMailer Contact Form</title>
<style>
label{
display: block;
}
</style>
</head>
<body>
<h4> <?php echo $result; ?> </h4> <!-- here is the problem -->
<form method="post" action="fetch.php">
<label>Name</label>
<input type="text" name="name"><br>
<label>E-mail</label>
<input type="email" name="email"><br>
<label>Subject</label>
<input type="text" name="subject"><br>
<label>Message</label>
<textarea rows="5" cols="40" name="message"></textarea><br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
fetch.php
<?php
/*
* To change this license header, choose License Headers in
Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//These lines must be at the top script
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$result=""; // this is the variable i asked about
if(isset($_POST['submit']))
{
$uname=$_POST['name'];
$uemail=$_POST['email'];
$usub=$_POST['subject'];
$umsg=$_POST['message'];
require 'vendor/autoload.php'; //composer's autoloader
$mail = new PHPMailer; //creat object
//Server settings
$mail->Host = 'smtp.gmail.com'; //SMTP server
$mail->isSMTP(); //set mailer to use smtp
$mail->SMTPAuth = true; //enable authentication
$mail->Username = 'my#gmail.com'; //smtp user name
$mail->Password = 'secrete'; // smtp password
$mail->SMTPSecure = 'tls'; //Enable TLS encryption
$mail->Port = 587; //Tcp port to connect
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'From Form :'.$usub; //subject
$mail->Body= '<h3>'
.'Name :'.$uname
.'<br>E-mail :'.$uemail
.'<br>Message :'.$umsg
. '</h3>';`enter code here`
//Recipients
$mail->setFrom($uemail,$uname);
$mail->addAddress('my#gmail.com', 'to User');
$mail->addReplyTo($uemail,$uname);
if(!$mail->send()) //send mail
{
$result = "Message could not be sent.";
}
else
{
$result ="Thank you ".$uname." for contacting us.";
}
}
You have two options,
1. Use sessions
In fetch.php put this code at the end
$ _SESSION['result'] = $result ;
And then you can access
$_SESSION['result'];
in index.php
In order to initialize sessions put
session_start();
at the top of both files.
2. Url parameter
In fetch.php add this at the end
header('Location: index.php?result='.$result);
Then you can access this url parameter in index.php as follows,
$_GET['result'];
index.php
<?php
if(!session_id()) session_start();
?>
<!DOCTYPE html>
<!-- -->
<html>
<head>
<meta charset="UTF-8">
<title>PHPMailer Contact Form</title>
<style>
label{
display: block;
}
</style>
</head>
<body>
<h4> <?php if(isset($_SESSION['result'])){ echo $_SESSION['result']; $_SESSION['result']=''; } ?> </h4> <!-- here is the problem -->
<form method="post" action="fetch.php">
<label>Name</label>
<input type="text" name="name"><br>
<label>E-mail</label>
<input type="email" name="email"><br>
<label>Subject</label>
<input type="text" name="subject"><br>
<label>Message</label>
<textarea rows="5" cols="40" name="message"></textarea><br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
fetch.php
<?php
/*
* To change this license header, choose License Headers in
Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//These lines must be at the top script
if(!session_id()) session_start();
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$result=""; // this is the variable i asked about
if(isset($_POST['submit']))
{
$uname=$_POST['name'];
$uemail=$_POST['email'];
$usub=$_POST['subject'];
$umsg=$_POST['message'];
require 'vendor/autoload.php'; //composer's autoloader
$mail = new PHPMailer; //creat object
//Server settings
$mail->Host = 'smtp.gmail.com'; //SMTP server
$mail->isSMTP(); //set mailer to use smtp
$mail->SMTPAuth = true; //enable authentication
$mail->Username = 'my#gmail.com'; //smtp user name
$mail->Password = 'secrete'; // smtp password
$mail->SMTPSecure = 'tls'; //Enable TLS encryption
$mail->Port = 587; //Tcp port to connect
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'From Form :'.$usub; //subject
$mail->Body= '<h3>'
.'Name :'.$uname
.'<br>E-mail :'.$uemail
.'<br>Message :'.$umsg
. '</h3>';`enter code here`
//Recipients
$mail->setFrom($uemail,$uname);
$mail->addAddress('my#gmail.com', 'to User');
$mail->addReplyTo($uemail,$uname);
if(!$mail->send()) //send mail
{
$result = "Message could not be sent.";
}
else
{
$result ="Thank you ".$uname." for contacting us.";
}
$_SESSION['result'] = $result;
}
header('Location: index.php');

How to send PHP email after posting data to Database

I am currently working on a quote form. After submitting the form, there was an email set to send submitted record back to client as copy. However, as I was using Mandrill for transaction emails, it's no longer free. I don't want to use any paid service and am now looking to send the same email using PHPMailer. I am finding it difficult to understand to call php to send email. Any help? I am open for options. All I want to send email after form submits.
email.js
function finalize_things(data, order_id){
//posting data to the server side page
$.post(window.location.origin+'/post/', data,function(response){
if(response == 'success'){
console.log(response);
send_email(order_id, data.email, data.firstname, data.project_details, data.file_names);
} else {
console.log(response);
alert('order not placed.');}
});
}
function send_email(order_id, email, firstname, project_details, file_names){
var html_message = "message here"
data = {
"key": "xxxxxxxxx",
"message": {
"html": html_message,
"text": "",
"subject": "Your subject",
"from_email": "test#test.com",
"from_name": "Company name",
"to": [{
"email": email,
"name": firstname
}
]},
"async": false
};
$.ajax({url: 'https://mandrillapp.com/api/1.0/messages/send.json',
type: 'POST',
data: data,
success: function(resp){
console.log(resp); }
});
PHPMAILER Code:
include_once '/../../PHPMailer/cms_db.php';
require_once '/../../PHPMailer/PHPMailerAutoload.php';
require_once '/../../PHPMailer/config.php';
if (isset($_POST["email"]) && !empty($_POST["email"])) {
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Host = $smtp_server; // Specify main and backup SMTP servers
$mail->Username = $username; // SMTP username
$mail->Password = $password; // SMTP password
$mail->SMTPSecure = "tls"; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom("companyemail#xyz.com", "Company Name");
$mail->addAddress($email, $firstname); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$bodyContent = "test message";
$mail->Subject = "Your Quote ID";
$mail->Body = $bodyContent;
$mail->AltBody = $bodyContent;
if(!$mail->send()) {
echo "Message could not be sent.";
$error = '<div class="alert alert-danger"><strong>Mailer Error: '. $mail->ErrorInfo.'</strong></div>';
} else {
$error = '<div class="alert alert-success"><strong>Message has been sent</strong></div>';
}
}
So, if you don't want to use external services like gmail... You need to set up your own mail server (postfix, sendmail etc.) Please note, that webservers very often has potfix onboard (httpd + php + mysql + postfix) already.
Has your hosting postfix already? Check this by using standard mail function, php script like :
<?php
$to = 'yourmail#gmail.com';
$subject = 'test subj';
$mail_body = 'test body';
mail($to, $subject, $mail_body);
?>
If it works -- write your own script based on this code or use phpmailer (it has settings for local mail daemon)
PS PHPMailer can send mail via extenal webserver, like gmail https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps (key line here: $mail->isSMTP();) or via local server, such as postfix -- see example here -- key line is $mail->isSendmail();
and your current code snippet is for using EXTERNAL service, not for LOCAL!
Changes in your js this line:
$.ajax({url: 'https://mandrillapp.com/api/1.0/messages/send.json',
to:
$.ajax({url: 'http://yourserver.tld/send_phpmailer.php',
And use something like this in send_phpmailer.php:
<?php
////// Part 1. Set up variables
$key = $_POST['key']; // need for mandrill, you can omit this
$html = $_POST['message']['html'];
$text = $_POST['message']['text'];
$subject = $_POST['message']['subject'];
$from_email = $_POST['message']['from_email'];
$from_name = $_POST['message']['from_name'];
$to_email = $_POST['message']['to']['email'];
$to_name = $_POST['message']['to']['name'];
////// Part 2. Including PHPMailer
include_once '/../../PHPMailer/cms_db.php';
require_once '/../../PHPMailer/PHPMailerAutoload.php';
require_once '/../../PHPMailer/config.php';
////// Part 3. Sending letter by PHPMailer
$mail = new PHPMailer;
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "username#gmail.com";
$mail->Password = "yourpassword";
//Set who the message is to be sent from
$mail->setFrom( $from_email, $from_name);
//Set an alternative reply-to address
//$mail->addReplyTo('replyto#example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress($to_email, $to_name);
//Set the subject line
$mail->Subject = $subject;
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML($html);
//Replace the plain text body with one created manually
$mail->AltBody = $text;
//Attach an image file
//$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
<?php
include ('config.php');
if(isset($_POST['submit']))
{
$name=mysqli_real_escape_string($conn,$_POST['name']);
$email=mysqli_real_escape_string($conn,$_POST['email']);
$phone=mysqli_real_escape_string($conn,$_POST['phone']);
$msg=mysqli_real_escape_string($conn,$_POST['msg']);
$sql="insert into contact(`name`,`email`,`phone`,`msg`) values('$name','$email','$phone','$msg')";
// $result=mysqli_query($conn,$sql);
if(mysqli_query($conn, $sql)){
$to='akhilsai.innovkraft#gmail.com'; // Receiver Email ID, Replace with your email ID
$subject='Form Submission';
$message="Name :".$name."\n"."Phone :".$phone."\n"."Wrote the following :"."\n\n".$msg;
$headers="From: ".$email;
$sentmail=swiftmail($to, $subject, $message, $headers);
header('localtion:index.html');
}
else{
echo "ERROR:";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Feedback Form</title>
</head>
<body>
<div class="main">
<div class="info">Give Your Feedback!</div>
<form action="#" method="post" name="form" class="form-box">
<label for="name">Name</label><br>
<input type="text" name="name" class="inp" placeholder="Enter Your Name" required><br>
<label for="email">Email ID</label><br>
<input type="email" name="email" class="inp" placeholder="Enter Your Email" required><br>
<label for="phone">Phone</label><br>
<input type="tel" name="phone" class="inp" placeholder="Enter Your Phone" required><br>
<label for="message">Message</label><br>
<textarea name="msg" class="msg-box" placeholder="Enter Your Message Here..." required></textarea><br>
<input type="submit" name="submit" value="Send" class="sub-btn">
</form>
</div>
</body>
</html>
i try this coding in my own way
<?php
include ('config.php');
if(isset($_POST['submit']))
{
$name=mysqli_real_escape_string($conn,$_POST['name']);
$email=mysqli_real_escape_string($conn,$_POST['email']);
$phone=mysqli_real_escape_string($conn,$_POST['phone']);
$msg=mysqli_real_escape_string($conn,$_POST['msg']);
$sql="insert into contact(`name`,`email`,`phone`,`msg`) values('$name','$email','$phone','$msg')";
// $result=mysqli_query($conn,$sql);
if(mysqli_query($conn, $sql)){
$to='akhilsai.innovkraft#gmail.com'; // Receiver Email ID, Replace with your email ID
$subject='Form Submission';
$message="Name :".$name."\n"."Phone :".$phone."\n"."Wrote the following :"."\n\n".$msg;
$headers="From: ".$email;
$sentmail=swiftmail($to, $subject, $message, $headers);
header('localtion:index.html');
}
else{
echo "ERROR:";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Feedback Form</title>
</head>
<body>
<div class="main">
<div class="info">Give Your Feedback!</div>
<form action="#" method="post" name="form" class="form-box">
<label for="name">Name</label><br>
<input type="text" name="name" class="inp" placeholder="Enter Your Name" required><br>
<label for="email">Email ID</label><br>
<input type="email" name="email" class="inp" placeholder="Enter Your Email" required><br>
<label for="phone">Phone</label><br>
<input type="tel" name="phone" class="inp" placeholder="Enter Your Phone" required><br>
<label for="message">Message</label><br>
<textarea name="msg" class="msg-box" placeholder="Enter Your Message Here..." required></textarea><br>
<input type="submit" name="submit" value="Send" class="sub-btn">
</form>
</div>
</body>
</html>

Categories