Issue with PHPmailer and Google reCapcha V2 validation - php

I'm having issues with Google reCapcha verification in a form using PHPmailer. When the form is completed and the check in "I'm not a robot" is ok, press SEND and this message appears:
"reCaptcha is not Valid! Please try again.".
I've tried with reloading, change navigator to latest version, delete historial, and nothing works.
This is the message in the Google reCapcha admin panel: "We have detected that your website does not verify reCAPTCHA solutions. These verifications are necessary for the service to function properly on your website. You can get more information on our developer website".
Furthermore, I've set the allow_url_fopen = on for testing, but still doesn't work.
Does anyone figure out what's going on, and what's the best solution?
Actualization 13/06:
The ERROR_LOG shows this:
[13-Jun-2021 21:20:22 UTC] PHP Warning: file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /home/mywebsite/public_html/include/contact-form.php on line 90
[13-Jun-2021 21:20:22 UTC] PHP Warning: file_get_contents(https://www.google.com/recaptcha/api/siteverify?secret=XX--very long code here--XX): failed to open stream: no suitable wrapper could be found in /home/mywebsite/public_html/include/contact-form.php on line 90
The contact-form.PHP file original is this:
<?php
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'php-mailer/src/Exception.php';
require 'php-mailer/src/PHPMailer.php';
//require 'php-mailer/src/SMTP.php';
// Enter your email address. If you need multiple email recipes simply add a comma: email#domain.com, email2#domain.com
$to = "";
// Add your reCaptcha Secret key if you wish to activate google reCaptcha security
$recaptcha_secret_key = '';
// Default message responses
const RESPONSE_MSG = [
'success' => [
"message_sent" => "We have <strong>successfully</strong> received your message. We will get back to you as soon as possible."
],
'form' => [
"recipient_email" => "Message not sent! The recipient email address is missing in the config file.",
"name" => "Contact Form",
"subject" => "New Message From Contact Form"
],
'google' => [
"recapthca_invalid" => "reCaptcha is not Valid! Please try again.",
"recaptcha_secret_key" => "Google reCaptcha secret key is missing in config file!"
]
];
//This functionality will process post fields without worrying to define them on your html template for your customzied form.
//Note: autofields will process only post fields that starts with name widget-contact-form OR with custom prefix field name
$form_prefix = isset($_POST["form-prefix"]) ? $_POST["form-prefix"] : "widget-contact-form-";
$form_title = isset($_POST["form-name"]) ? $_POST["form-name"] : RESPONSE_MSG['form']['name'];
$subject = isset($_POST[$form_prefix."subject"]) ? $_POST[$form_prefix."subject"] : RESPONSE_MSG['form']['subject'];
$email = isset($_POST[$form_prefix."email"]) ? $_POST[$form_prefix."email"] : null;
$name = isset($_POST[$form_prefix."name"]) ? $_POST[$form_prefix."name"] : null;
if( $_SERVER['REQUEST_METHOD'] == 'POST') {
if($email != '') {
if(empty($to)) {
$response = array ('response'=>'warning', 'message'=> RESPONSE_MSG['form']['recipient_email']);
echo json_encode($response);
die;
}
//If you don't receive the email, enable and configure these parameters below:
//$mail->SMTPOptions = array('ssl' => array('verify_peer' => false,'verify_peer_name' => false,'allow_self_signed' => true));
//$mail->IsSMTP();
//$mail->Host = 'mail.yourserver.com'; // Specify main and backup SMTP servers, example: smtp1.example.com;smtp2.example.com
//$mail->SMTPAuth = true;
//$mail->Port = 587; // TCP port to connect to 587 or 465
//$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
//$mail->Username = 'SMTP username'; // SMTP username
//$mail->Password = 'SMTP password'; // SMTP password
$mail = new PHPMailer;
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';
$mail->From = $email;
$mail->FromName = $name;
if(strpos($to, ',') !== false){
$email_addresses = explode(',', $to);
foreach($email_addresses as $email_address) {
$mail->AddAddress(trim($email_address));
}
}
else {$mail->AddAddress($to);}
$mail->AddReplyTo($email, $name);
$mail->Subject = $subject;
// Check if google captch is present
if(isset($_POST['g-recaptcha-response'])) {
if(empty($recaptcha_secret_key)) {
$response = array ('response'=>'error', 'message'=> RESPONSE_MSG['google']['recaptcha_secret_key']);
echo json_encode($response);
die;
}
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$recaptcha_secret_key.'&response='.$_POST['g-recaptcha-response']);
$response_data = json_decode($response);
if ($response_data->success !== true ) {
$response = array ('response'=>'error', 'message'=> RESPONSE_MSG['google']['recapthca_invalid']);
echo json_encode($response);
die;
}
}
//Remove unused fields
foreach (array("form-prefix", "subject", "g-recaptcha") as $fld) {
unset($_POST[$form_prefix . $fld]);
}
unset($_POST['g-recaptcha-response']);
//Format eMail Template
$mail_template = '<table width="100%" cellspacing="40" cellpadding="0" bgcolor="#F5F5F5"><tbody><tr><td>';
$mail_template .= '<table width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#F5F5F5" style="border-spacing:0;font-family:sans-serif;color:#475159;margin:0 auto;width:100%;max-width:70%"><tbody>';
$mail_template .= '<tr><td style="padding-top:20px;padding-left:0px;padding-right:0px;width:100%;text-align:right; font-size:12px;line-height:22px">This email is sent from '.$_SERVER['HTTP_HOST'].'</td></tr>';
$mail_template .= '</tbody></table>';
$mail_template .= '<table width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#F5F5F5" style="padding: 50px; border-spacing:0;font-family:sans-serif;color:#475159;margin:0 auto;width:100%;max-width:70%; background-color:#ffffff;"><tbody>';
$mail_template .= '<tr><td style="font-weight:bold;font-family:Arial,sans-serif;font-size:36px;line-height:42px">'.$form_title.'</td></tr>';
$mail_template .= '<tr><td style="padding-top:25px;padding-bottom:40px; font-size:16px;">';
foreach ($_POST as $field => $value) {
$split_field_name = str_replace($form_prefix, '', $field);
$ucwords_field_name = ucfirst(str_replace('-', ' ', $split_field_name));
$mail_template .= '<p style="display:block;margin-bottom:10px;"><strong>'.$ucwords_field_name.': </strong>'.$value.'</p>';
}
$mail_template .= '</td></tr>';
$mail_template .= '<tr><td style="padding-top:16px;font-size:12px;line-height:24px;color:#767676; border-top:1px solid #f5f7f8;">Date: '.date("F j, Y, g:i a").'</td></tr>';
$mail_template .= '<tr><td style="font-size:12px;line-height:24px;color:#767676">From: '.$email.'</td></tr>';
$mail_template .= '</tbody></table>';
$mail_template .= '</td></tr></tbody></table>';
$mail->Body = $mail_template;
// Check if any file is attached
$attachments = [];
if (!empty($_FILES[$form_prefix.'attachment'])) {
$result = array();
foreach ($_FILES[$form_prefix.'attachment'] as $key => $value) {
for ($i = 0; $i < count($value); $i++) {
$result[$i][$key] = $value[$i];
}
}
foreach ( $result as $key => $attachment) {
$mail->addAttachment($attachment['tmp_name'],$attachment['name']);
}
}
if(!$mail->Send()) {
$response = array ('response'=>'error', 'message'=> $mail->ErrorInfo);
}else {
$response = array ('response'=>'success', 'message'=> RESPONSE_MSG['success']['message_sent']);
}
echo json_encode($response);
} else {
$response = array ('response'=>'error');
echo json_encode($response);
}
}
?>
Thank you,
Alejandra

Related

Get form data from one wordpress function to another while using a restApi in a custom plugin

i have two rest api end points for the Calculator and another for the email submission.
i want to include the data from calculator to the email handler function.
Calculator Handler:
// function for the endpoint for form
add_action('rest_api_init', 'create_rest_endpoint');
function create_rest_endpoint() {
// Create endpoint for front end to connect to WordPress securely to post form data
register_rest_route('bohio/v1', 'submit', array(
'methods' => 'POST',
'callback' => 'handle_query',
'permission_callback' => '__return_true'
));
}
// callback method
function handle_query($data) {
// Handle the form data that is posted
// Get all parameters from form
$output = $data->get_params();
// form fields : service, bed, bath,square_feet,cadence
}
Email handler:
function handle_email($data) {
// Handle the form data that is posted
// Get all parameters from form
$emailData = $data->get_params();
// Set fields from the form
$field_name = sanitize_text_field($emailData['name']);
$field_email = sanitize_email($emailData['email']);
//Check if nonce is valid, if not, respond back with error
if (!wp_verify_nonce($emailData['_wpnonce'], 'wp_rest')) {
return new WP_Rest_Response('Message not sent', 422);
}
else {
// Remove unneeded data from paramaters
unset($emailData['_wpnonce']);
unset($emailData['_wp_http_referer']);
// Send the email message
$headers = [];
// $admin_email = get_bloginfo('admin_email');
$admin_email = get_option('bh_email_sub');
// var_dump($admin_email);
$from_email = get_option('bh_email_sub');
$admin_name = get_option('bh_admin_sub_name');
// $admin_name = get_bloginfo('name');
// Set admin email as recipient email if no option has been set
$recipient_email = $admin_email;
$headers[] = "From: {$admin_name} <{$from_email}>";
$headers[] = "Reply-to: {$field_name} <{$field_email}>";
$headers[] = "Content-Type: text/html";
$subject = "New email submission from {$field_name}";
$message = '';
$message = "<h2>New Email submission from {$field_name}</h2>";
// Loop through each field posted and sanitize it
foreach ($emailData as $label => $value) {
switch ($label) {
case 'message':
$value = sanitize_textarea_field($value);
break;
case 'email':
$value = sanitize_email($value);
break;
default:
$value = sanitize_text_field($value);
}
$message .= '<strong>' . sanitize_text_field(ucfirst($label)) . ':</strong> ' . $value . '<br />';
}
wp_mail($recipient_email, $subject, $message, $headers);
$confirmation_message = "The message was sent successfully!!";
// return $confirmation_message;
return $confirmation_message;
}
}
How would i access the data from handle_query to handle_email and send via email. Both functions lies in the same file of a plugin.

Weird Behavior of Google ReCaptcha V2

I am using PHP Mailer to mail the details of a form to a particular Email Address. But before that the code checks the server side validation of Google Recaptcha Version 2. I am facing this weird behavior where the server validation is always returning me false. I am not able to figure out why? I have double-checked the site and secret keys and both are as defined my google account. Following is the code:
<?php
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';
require 'PHPMailer-master/src/Exception.php';
if(isset($_POST['submit']))
{
$captcha;
$target_dir = "Upload_Attachment/";
$name = htmlentities($_POST['name']);
$email = htmlentities($_POST['email']);
$mobile = htmlentities($_POST['mobile']);
$edu_qual = htmlentities($_POST['edu_qual']);
$years_exp = htmlentities($_POST['years_exp']);
$comments = htmlentities($_POST['frmrequirements']);
if(isset($_POST['g-recaptcha-response']))
{
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha)
{
echo '<script>alert("Something Went Wrong!");</script>';
exit;
}
$secretKey = "MY_SECRET_KEY";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo '<script>alert("Something Went Wrong!");</script>';
exit;
}
else
{
$ds= DIRECTORY_SEPARATOR;
$target_dir = "resume_files".$ds;
$target_file = $target_dir . basename($_FILES["my_File"]["name"]);
if (move_uploaded_file($_FILES["my_File"]["tmp_name"], $target_file))
{
//echo "The file ". basename($file). " has been uploaded.";
}
else
{
echo '<script>alert("Something Went Wrong!");</script>';
}
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP(); // enable SMTP
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->isHTML();
$mail->Username = "MY_USER_NAME";
$mail->Password = "MY_PASSWORD";
$mail->SetFrom("MY_EMAIL");
$mail->Subject = "Job Enquiry from ".$_POST['name'];
$mail->Body = "
<html>
<body>
<table cellspacing = '5' cellpadding = '5' border='2'>
<tr>
<td>Name:</td>
<td>".$name."</td>
</tr>
<tr>
<td>Email ID:</td>
<td>".$email."</td>
</tr>
<tr>
<td>Mobile No:</td>
<td>".$mobile."</td>
</tr>
<tr>
<td>Years of Experience:</td>
<td>".$years_exp."</td>
</tr>
<tr>
<td>Educational Qualification:</td>
<td>".$edu_qual."</td>
</tr>
<tr>
<td>Comments:</td>
<td>".$comments."</td>
</tr>
</table>
</body>
</html>
";
$mail->addAttachment($target_file);
$mail->AddAddress("TARGET_EMAIL_ID");
if(!$mail->Send())
{
echo '<script>alert("Something Went Wrong!");</script>';
}
else
{
unlink($target_file);
}
echo "<script>location='careers?success=1'</script>";
}
}
?>
Please help me.
It looks like you're using a GET request instead of POST to query Google.
You can build a POST request using stream_context_create.
Example:
$data = ['secret' => $secret, 'response' => $response, 'remoteip' => $ip];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents("https://www.google.com/recaptcha/api/siteverify", false, $context);

Sending mail with api data using codeigniter

I need to send mail to the admin with the inserted data using APi function ,
the function is look like that
public function requestbookingresort_post()
{
$languageid = $this->input->post('languageId');
$resort_id = $this->input->post('resortId');
$booking_from = $this->input->post('bookingFrom');
$booking_to = $this->input->post('bookingTo');
$contact_name = $this->input->post('contactName');
$contact_email = $this->input->post('contactEmail');
$contact_phone = $this->input->post('contactPhone');
$userid = $this->input->post('userId');
if (empty($languageid))
{
$languageRecord = getDefaultlanguage();
$languageid = $languageRecord->languageid;
}
$language_file = languagefilebyid($languageid);
$this->lang->load($language_file, $language_file);
if (empty($resort_id) || empty($booking_from) || empty($booking_to) || empty($contact_name) || empty($contact_email) || empty($contact_phone))
{
$arr['status'] = 'error';
$arr['statusMessage'] = lang('error_in_booking');
$arr['data'] = array();
}
else
{
$dataArray = array(
"languageid" => $languageid,
"userid" => empty($userid) ? "0" : $userid,
"resortid" => $resort_id,
"bookingfrom" => date("Y-m-d", strtotime($booking_from)),
"bookingto" => date("Y-m-d", strtotime($booking_to)),
"contactname" => $contact_name,
"contactemail" => $contact_email,
"contactphone" => $contact_phone,
"requestdatetime" => date("Y-m-d H:i:s"),
);
$this->load->model("Resort_model");
$booking_id = $this->Resort_model->saveBookingRequest($dataArray);
if (empty($booking_id))
{
$arr['status'] = 'error';
$arr['statusMessage'] = lang('error_occurred');
$arr['data'] = array();
}
else
{
$arr['status'] = 'success';
$arr['statusMessage'] = lang('booking_request_submit');
$arr['data'] = array();
}
}
$response = array(
"response" => $arr
);
$this->set_response($response, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
But i'm new at codeigniter and didn't know how to get this passed data from the database to send mail with that to the admin mail or something ?
Try this.
public function requestbookingresort_post()
{
// Your operations
$response = array(
"response" => $arr
);
$this->sendMail($response)
$this->set_response($response, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
public function sendMail($response)
{
$settings=$this->Some_model->getEmailSettings();
$mail = new PHPMailer();
$mail->IsSMTP(); // we are going to use SMTP
$mail->SMTPAuth = true; // enabled SMTP authentication
$mail->SMTPSecure = "ssl"; // prefix for secure protocol to connect to the server
$mail->Host = $settings->host; // setting GMail as our SMTP server
$mail->Port = $settings->port; // SMTP port to connect to GMail
$mail->Username = $settings->email; // user email address
$mail->Password = $settings->password; // password in GMail
$mail->SetFrom($settings->sent_email, $settings->sent_title); //Who is sending the email
$mail->AddReplyTo($settings->reply_email,$settings->reply_email); //email address that receives the response
$mail->Subject = "Your Booking has been confirmed";
$mail->IsHTML(true);
$body = $this->load->view('path/email_template', $response, true);
$mail->MsgHTML($body);
$destination = $response['contactEmail']; // Who is addressed the email to
$mail->AddAddress($destination);
if(!$mail->Send()) {
$data['code']=300;
$data["message"] = "Error: " . $mail->ErrorInfo;
}
}
Make sure you have PHPMailer in your libraries and you are loading the library in your constructor and I hope you are keeping Email settings in your database. If not you can manually provide host, port, username and password fields

Zend_mail success message comes but mail not send

guys i have using a script to send mails, all seems fine with it and even i get the success message but sadly the emails are not delivered.. can any body look for any lapses in this code
Code
$body = "This is testmail please ignore";
$mail = new Zend_Mail ();
$tr = new Zend_Mail_Transport_Sendmail ( '-f' . $sentFromEmail );
Zend_Mail::setDefaultTransport ( $tr );
$mail->setReturnPath("user#admin.com");
$mail->setFrom ( "user#admin.com", 'Reporters' );
$mail->setBodyHtml ( $body );
$mail->addTo ( "samjam#gmail.com" );
$mail->setSubject ( "Weekly Report" );
try {
$mail->send ();
echo "Success";
} catch ( Exception $e ) {
echo "Mail sending failed.\n";
}
SMTP configuration
if (isset($config['ssl'])) {
switch (strtolower($config['ssl'])) {
case 'tls':
$this->_secure = 'tls';
break;
case 'ssl':
$this->_transport = 'ssl';
$this->_secure = 'ssl';
if ($port == null) {
$port = 465;
}
break;
}
}
if ($port == null) {
if (($port = ini_get('smtp_port')) == '') {
$port = 25;
}
}
The answer is that samjam#gmail.com is not an email address of any email account that you have access to.
It belongs to a private individual who you do not know.
This is the correct answer.

Yii Mailer doesn't work

I trying to send mail using yii simple mailer ...
I followed the step :
http://www.yiiframework.com/extension/yii-simple-mailer/
And download the extension and put in yii extension folder :
https://github.com/tlikai/YiiMailer
Then put the code to config/main.php:
'mailer' => array(
// for smtp
'class' => 'ext.mailer.SmtpMailer',
'server' => 'theserver',
'port' => '25',
'username' => 'theadmin',
'password' => 'thepassword',
// for php mail
'class' => 'ext.mailer.PhpMailer',
),
Then in my controller I wrote this code to send mail:
$to = 'wahaha#gmail.com';
$subject = 'Hello Mailer';
$content = 'Some content';
Yii::app()->mailer->send($to, $subject, $content);
Then the browser gave me the error :
Property "PhpMailer.server" is not defined.
Did I miss something in my code?
In config/main.php
'Smtpmail'=>array(
'class'=>'ext.smtpmail.PHPMailer',
'Host'=>"localhost",
'Username'=>'thesmile1019#gmail.com',
'Password'=>'wakakaka',
'Mailer'=>'smtp',
'Port'=>25,
'SMTPAuth'=>true,
),
In Component/controller.php
public function mailsend($to,$from,$from_name,$subject,$message)
{
$mail = Yii::app()->Smtpmail;
$mail->SetFrom($from,$from_name);
$mail->Subject = $subject;
$mail->MsgHTML($message);
$mail->AddAddress($to, "");
// Add CC
if(!empty($cc)){
foreach($cc as $email){
$mail->AddCC($email);
}
}
// Add Attchments
if(!empty($attachment)){
foreach($attachment as $attach){
$mail->AddAttachment($attach);
}
}
if(!$mail->Send()) {
return false; // Fail echo "Mailer Error: " . $mail->ErrorInfo;
}else {
return true; // Success
}
}
In controller
public function actionSendMail(){
$token = $_POST['YII_CSRF_TOKEN'];
if ($token !== Yii::app()->getRequest()->getCsrfToken()){
Yii::app()->end();
}
$to = 'thesmile1019#gmail.com';
$from = 'localhost';
$from_name = 'mface';
$subject = 'testing';
$message = 'testing';
if($token == true){
$util = new Utility();
$util->detectMobileBrowser();
$util->checkWebSiteLanguageInCookies();
$this->layout = "masterLayout";
$this->render('mailsend');
$this->mailsend($to,$from,$from_name,$subject,$message);
}else{
print_r("Not Sent");
die();
}
}
Process not problem going correct but didn't receive the mail
Change your port in pathtowebroot/protected/config/main.php
'Smtpmail'=>array(
'class'=>'ext.smtpmail.PHPMailer',
'Host'=>"smtp.gmail.com",
'Username'=>'thesmile1019#gmail.com',
'Password'=>'wakakaka',
'Mailer'=>'smtp',
'Port'=>465,
'SMTPAuth'=>true,
'SMTPSecure' => 'ssl'
),

Categories