PHPMailer SMTP troubles - Getting letters but with errors on the website - javascript

I have the following issue: I have a contact form on my Bootstrap 4 .html website. The form is a simple form based on PHPMailer with Bootstrap validator. Previously I received the emails from my contact form without SMTP and everything was fine. Now I decided to use Gmail SMTP and changed my code. I'm receiving the messages to my gmail inbox but I see the errors on the website as soon as the letter is sent.
Could, you, please, let me know where my problem is? I broke my head trying to solve the problem.
ajax.js file:
$(document).ready(function() {
function submitForm(){
var name =$("input[name=name]").val();
var email =$("input[name=email]").val();
var comment =$("textarea[name=comment]").val();
var captcha=grecaptcha.getResponse();
var form = $('form')[0];
var formData = new FormData(form);
formData.append('name', name );
formData.append('email', email );
formData.append('comment', comment );
formData.append('captcha', captcha );
$.ajax({
url: "include/ajax/send.php",
type: "POST",
contentType: false,
processData: false,
data: formData,
cache: false,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
php file:
// send email
$mail = new PHPMailer;
// Email Template
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 465;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'ssl';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "xxx#gmail.com";
//Password to use for SMTP authentication
$mail->Password = "xxx";
/* Replace the email address and the Email Subject */
$EmailTo = "xxx#gmail.com"; // The Send To Email
$Subject= "New Message"; // Email Subject
// reCAPTCHA SEcret Key
$reCaptchaSecretKey = "xxx";
//retrive form variables from ajax
$name =#$_REQUEST["name"];
$email =#$_POST["email"];
$comment =#$_POST["comment"];
$captcha=#$_REQUEST["captcha"];
$formGoogleCaptcha = $captcha;
//check Catptcha
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$reCaptchaSecretKey."&response=".$formGoogleCaptcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
$obj = json_decode($response);
if ($obj->success == 1 || $obj->success == true) {
$email_body="";
$email_body = $email_body . "<strong>First Name: </strong>" . $name . "\r\n\r\n";
$email_body = $email_body . "<strong>Email: </strong>" . $email . "\r\n\r\n";
$email_body = $email_body . "<strong>Message: </strong>" . $comment . "\r\n\r\n";
$email_body = nl2br($email_body);
$mail->SMTPDebug = 1;
I also attached an error example
Thank you in advance, mates.

What you're seeing is debug output, which is appearing because you have debug output enabled. Change this:
$mail->SMTPDebug = 1;
to
$mail->SMTPDebug = 0;
Note that you turn it off early in your script, but then turn it on again later.
A separate problem is that you're using a very old version of PHPMailer. Get the latest.

Related

How to change the me when receiving email on contact us

I've created an contact us form using PHP Mailer, however the problem is when I received the email the name before you open it is me and I can't figured out how to fix it. Also I appreciate it if someone explain to me what is the different between Username and the add Address. Thank you in advance.
Here is the me I'm referring to
<?php
use PHPMailer;
if(isset($_POST['name']) && isset($_POST['email'])){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$body = $_POST['body'];
require_once "PHPMailer/PHPMailer.php";
require_once "PHPMailer/SMTP.php";
require_once "PHPMailer/Exception.php";
$mail = new PHPMailer();
//smtp settings
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = "";
$mail->Password = '';
$mail->Port = 465;
$mail->SMTPSecure = "ssl";
$mail->SetFrom("$email ", "$name");
//email settings
$mail->isHTML(true);
$mail->setFrom($_POST['email'], $_POST['email']);
$mail->addAddress("");
$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)));
}
You are sending mail from the same email address to the same email address.
So, many email clients identify yourself as me.
You will have to send using another email address, and you will be idenfied with your email/name.
As Jesse said: You can also send mail to another email, and it will usually not show me.
Make a new Email address / use another Email address in script

I cant get my php mailer to send a mail using post data

i am having some trouble with phpmailer and ajax. Im quite new to ajax and dont fully understand it yet so this might have a quite obvious fix but here we go.
So when i just put my php mailer script in a page and visit it with set values i can send the mail. but whenever i try to send my form data to the script something doesnt work.
This is my jquery
$(document).ready(function(){
$(".contact-form").on("submit",function(e){
e.preventDefault();
function validateEmail($email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test( $email );
}
var valid = true;
if(!$("#name").val()) {
$("#userEmail").css('border','2px solid #FFFFDF');
valid = false;
}
if( !validateEmail($(' #email').val())) {
valid = false
}
if(!$("#subject").val()) {
$("#subject").css('border','2px solid #FFFFDF');
valid = false;
}
if(!$("#message").val()) {
$("#message").css('border','2px solid #FFFFDF');
valid = false;
}
//send data to php file
var isValid;
isValid = valid
if(isValid) {
var name = $("#name").val();
var email = $("#email").val();
var subject = $("#subject").val();
var message = $("#message").val();
jQuery.ajax({
url: "includes/sendmail.inc.php",
type : "POST",
data:{name:name,email:email,subject:subject,message:message},
success:function(data){
$(".err_msg").text("Send!");
$(".err_msg").css('background-color', 'green')
$(".err_msg").show()
},
error:function (){}
});
} else {
$(".err_msg").text("Oops! check your input.");
$(".err_msg").css('background-color', 'red')
$(".err_msg").show()
}
});
});
This is my php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// 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;
// Load Composer's autoloader
require 'vendor/autoload.php';
$name = $_POST['name'];
$mail = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'mail.example#example.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'example#example.com'; // SMTP username
$mail->Password = 'example123'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587 ; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom( $email , $name);
$mail->addAddress('example#example.com', 'John Doe'); // Add a recipient
$mail->addReplyTo($email , $name);
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
so this is what i have so far i hope you guys can figure out what i did wrong because i have been stuck on this for about two days now.
greetz Floris
yes i figured it out guys thanks ! so what went wrong is that for some reason it wouldnt send because the FROM email adress was a gmail account and i am using my own domain smtp that was causing it appearantly

Phpmailer and javascript configuration

I'm new to the world of programming. My code is shown below.
First question: how do I format the body text? For example, not having all requests in a row but one below the other, etc.
Second question: How can I insert the code to be able to load a file in my contact form, the html code is already present and it works but on the javascript side I can't understand where to insert it.
Last question: I have a news letters acceptance field how do I insert a field that tells me if the user has accepted the news letter?
Thanks a lot to everyone!
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$telefono = $_POST["telefono"];
$indirizzo = $_POST["indirizzo"];
$civico = $_POST["civico"];
$citta = $_POST["citta"];
$provincia = $_POST["provincia"];
$cap = $_POST["cap"];
$newsletters = $_POST["newsletters"];
$body = "Name:" .$name . "<br>Email:" . $email .
"TelefonoLocale:" . $telefono . "Indirizzo:" . $indirizzo . "Civico:" . $civico . "Città:" . $citta. "Provincia:" . $provincia . "Cap:" . $cap . "newsletters:" . $newsletters;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'xxxxxxx'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xxxxxxxx'; // SMTP username
$mail->Password = 'xxxxxxxxxx'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
$mail->Port = xxxxxx; // TCP port to connect to
//Recipients
$mail->setFrom('xxxxxx', $name);
$mail->addAddress('xxxxxxxx'); // Add a recipient
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = $body;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo '<script>
alert("Messaggio inviato correttamente");
window.history.go(-1);
</script>';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

How to reset ReCaptcha box on successful form submission

I have a form on my website that uses ReCaptcha2. After the form is successfully completed and you get the success message, the form fields (name, email, message) are cleared but the ReCaptcha box remains ticked. Is there any way to clear this box after successful submission of the form or is there a way to permanently show the success message (as opposed to it fading out after a few seconds) and remove the entire form from the page. Ideally the success message would remain on the page until it is refreshed. I still want the existing other error messages to fade in and out as they currently do.
At present the initial Captcha error message reads "You did not check the box, a bot was detected or you have already sent this form. Please check the box or refresh this page & try again". The refresh suggestion is to cover the instance where the user presses send again and ReCaptcha has been left ticked from a previous successful submission (ie they try to send the form twice). Hence why I would like to implement one of the solutions posed in my question. Thanks in advance for any help given. Here is working URL of the form (at the bottom of the page)
http://www.topolinowebdesigns.uk/test-site/aerocoat/index-v2.html
<?php
/*
+-----------------------------------------------------+
| GOOGLE reCAPTCHA YOUR PUBLIC AND PRIVATE KEY |
| You can collect public and secret key from here: |
| https://www.google.com/recaptcha/admin |
+-----------------------------------------------------+
*/
$recaptcha_secretkey = "My secret key";
// GOOGLE reCAPTCHA Validation Check
ini_set('display_errors',1); error_reporting(E_ALL);
$message = "";
$status = "false";
if( isset( $_POST['submit'] ) ) {
$userIP = $_SERVER["REMOTE_ADDR"];
$recaptchaResponse = $_POST['g-recaptcha-response'];
$secretKey = $recaptcha_secretkey;
$request = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secretKey}&response={$recaptchaResponse}&remoteip={$userIP}");
if( !strstr( $request, "true" ) ) {
$message = '<p align="justify"><strong>Captcha Error!</strong> You did not check the box, a bot was detected or you have already sent this form. Please check the box or refresh this page & try again.</p>';
$status = "false";
} else {
require_once('phpmailer/class.phpmailer.php');
require_once('phpmailer/class.smtp.php');
$mail = new PHPMailer();
//$mail->SMTPDebug = 3; // Enable verbose debug output
/*$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'my hostname'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'my username'; // SMTP username
$mail->Password = 'my password'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to*/
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if( $_POST['form_name'] != '' AND $_POST['form_email'] != '' ) {
$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_message'];
$subject = 'New Message | Contact Form';
$botcheck = $_POST['form_botcheck'];
$toemail = 'my email address'; // Your Email Address
$toname = 'my name'; // Your Name
if( $botcheck == '' ) {
$mail->SetFrom( $email , $name );
$mail->AddReplyTo( $email , $name );
$mail->AddAddress( $toemail , $toname );
$mail->Subject = $subject;
$name = isset($name) ? "Name: $name<br><br>" : '';
$email = isset($email) ? "Email: $email<br><br>" : '';
$message = isset($message) ? "Message: $message<br><br>" : '';
$referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>This form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';
$body = "$name $email $message $referrer";
$mail->MsgHTML( $body );
$sendEmail = $mail->Send();
if( $sendEmail == true ):
$message = '<p align="justify"><strong>Success!</strong> We have received your message and will get back to you as soon as possible.</p>';
$status = "true";
else:
$message = '<p align="justify"><strong>Attention!</strong> Your message could not be sent due to an unexpected error. Please try again later.<br /><br /><strong>Reason:</strong><br />' . $mail->ErrorInfo . '</p>';
$status = "false";
endif;
} else {
$message = '<p align="justify"><strong>Bot Detected!</strong> Your efforts are futile!</p>';
$status = "false";
}
} else {
$message = '<p align="justify"><strong>Warning!</strong> Please complete all the fields and try again.</p>';
$status = "false";
}
} else {
$message = '<p align="justify"><strong>Unexpected Error!</strong> Please try again later.</p>';
$status = "false";
}
}
$status_array = array( 'message' => $message, 'status' => $status);
echo json_encode($status_array);
}
?>
In addition here is the validation script that runs on the html page just after the form ends.
<script>
$("#contact_form").validate({
submitHandler: function(form) {
var form_btn = $(form).find('button[type="submit"]');
var form_result_div = '#form-result';
$(form_result_div).remove();
form_btn.before('<div id="form-result" class="alert alert-success" role="alert" style="display: none;"></div>');
var form_btn_old_msg = form_btn.html();
form_btn.html(form_btn.prop('disabled', true).data("loading-text"));
$(form).ajaxSubmit({
dataType: 'json',
success: function(data) {
if( data.status === 'true' ) {
$(form).find('.form-control').val('');
}
form_btn.prop('disabled', false).html(form_btn_old_msg);
$(form_result_div).html(data.message).fadeIn('slow');
setTimeout(function(){ $(form_result_div).fadeOut('slow') }, 8000);
}
});
}
});
</script>

How to set timeout in Account verification through gmail?

I tried many site but I can't find the result what I want to do.so anybody can please help me to solve this ?
My problem is :
I want to send forgot password email to client.which is expire after 15 min.Here is my code
function send_email($to, $subject, $message)
{
global $from_email;
global $from_pwd;
global $host;
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->ContentType = "text/html";
$mail->Host = $host;
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Username = $from_email;
$mail->Password = $from_pwd;
$mail->From = $from_email;
$mail->AddAddress($to);
$mail->Subject = $subject;
$mail->Body = $message;
if(!$mail->Send()) {
die('Message was not sent.'.$mail->ErrorInfo);
}
}
And I also Added This code
//Send Welcome Email
require_once("classes/class.phpmailer.php");
send_email($_POST["email"],"Thanks For Register", "Php Link is here");
There are so many ways to achieve this like:
While sending the email make an entry in the datatabse table with the time on email send and put the check to compare the time with given time limit and show the message if time exceeds.
Send an extra pramater in the link that contains timestamp or encrypted time in it, compare it with the time of clicked time and show the message.

Categories

Resources