Contact form submits regardless of Recaptcha - suspecting ajax validator - php

I've made a contact form for a website that works - so well that bots spam the company using it. Not good.
I've looked into adding a google recaptcha validation system.
I've succesfully added the widget to the website as well as gone so far as:
Website returns an error to the user if captcha isn't verified when they click submit.
Website shows correct affirmation message when captcha is verified and they press submit.
So far so good.
The issue:
The form sends regardless of the captcha. So regardless if it actually shows the error to the user about the captcha being verified or not, it still submits the message - ultimately making this bot stopping recaptcha worthless. It looks nice... but is it really? Not yet.
I suspect it's the .js validation script I have that does this. I've tried a few things like changing order of code around etc, but my newbie status really makes it hard and I'm close to giving up.
My form uses php, ajax for instant verification if form is sent, js and the good old html and css.
.PHP:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$firstname = ($_POST['firstname']);
$lastname = ($_POST['lastname']);
$phone = ($_POST['phone']);
$email = ($_POST['email']);
$message = ($_POST['message']);
$msg = ($_POST['msg']);
$okMessage = ' SUCCESS ';
$errorMessage = ' ERROR';
$secretKey = " EXAMPLE ";
$responseKey = $_POST['g-recaptcha-response'];
$userIP = $_SERVER['REMOTE_ADDR'];
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = ' EXAMPLE ';
$mail->SMTPAuth = true;
$mail->Username = ' EXAMPLE ';
$mail->Password = ' EXAMPLE ';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->WordWrap = 50;
$mail->Priority = 1;
$mail->CharSet = 'utf-8';
$mail->setFrom(' EXAMPLE ', ' EXAMPLE ');
$mail->addAddress(' EXAMPLE ');
$mail->addReplyTo($email);
$mail->isHTML(true);
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
$response = file_get_contents($url);
$response = json_decode($response);
$mail->Subject = 'NY BESKED - EXAMPLE';
$mail->Body = (' EXAMPLE ');
$mail->AltBody = (' EXAMPLE ');
if (!$mail->send() || !$response->success) {
throw new \Exception('ERROR TRY AGAIN' . $mail->ErrorInfo);
} else {
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
} catch (\Exception $e) {
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
} else {
echo $responseArray['message'];
}
JS PART:
$(function ValidateEmailForm() {
window.verifyRecaptchaCallback = function (response) {
$('input[data-recaptcha]').val(response).trigger('change')
};
window.expiredRecaptchaCallback = function () {
$('input[data-recaptcha]').val("").trigger('change')
};
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data) {
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
});
});
and the HTML part:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<div class="col-12 d-flex justify-content-center">
<div class="g-recaptcha" data-sitekey="6Lf80bUUAAAAADrnadBM_GYs0PY8p4QqP7ol45ac"></div>
</div>
What's the issue here? Thank you in advance!

Your conditions are backwards. You should check the captcha first:
if (!$response->success || !$mail->send()) {

Related

Issue with PHPmailer and Google reCapcha V2 validation

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

Send data from Google App Script to a php site

Trying to send data from Google App Script to a php site which sends an email from my database. For most of the date it is no problem I send it via the url(example.com/example.php?id=test&id2=test2&id3=test3).
For most of the data it is no problem except for the third parameter, the given value is way longer than the other two and may contain newlines as well. My idea was to send the third(or all values) as JSON object.
My Google AppScript code so far:
function sendData(){
var options = {'text' : 'A longer example text'} ;
try {
var url = "https://example.com/example.php?id1=test1&id2=test2&id3="+options;
var httpRequest = UrlFetchApp.fetch(url, options).getContentText();
}
catch(e){
Logger.log(e);
}
return;
}
My PHP code:
<?php
require 'includes/functions.php';
include_once 'config.php';
include 'ChromePhp.php';
$email = $_GET["id1"];
$name = $_GET["id2"];
$text = $_GET["id3"];
$json = json_decode($text, true);
ChromePhp::log($json->text);
if(strpos($text, "\n") !== FALSE) {
$text = str_replace("\n", "<br>", $text);
}
$replace_to_standard=[$name, $text];
$replace_standard =['nametochange', 'textochange'];
$delivery_added = str_replace($replace_standard, $replace_to_standard, file_get_contents('standardMail.html'));
echo "" . $delivery_added . "";
$m = new MailSender;
$m-> sendMail($email, $email, $delivery_added, "Mail All");
The chrome logger will log "null"
Any ideas?
Using an AJAX post as an example, you can use the POST capability of Google apps script to send a post request to your PHP file and process it using the $_POST function of PHP.
Try in you GAS:
var payload = {
'text' : 'A longer example text',
'email' : 'test#email.com'
};
var options = {
'method' : 'post',
'payload' : payload
};
//var text = String(jsonData.comment);
try {
var url = "https://etadres.nl/login/mailAll.php";
var httpRequest = UrlFetchApp.fetch(url, options).getContentText();
}
catch(e){
Logger.log(e);
}
Catch your POST request in PHP and edit it as follows:
<?php
require 'includes/functions.php';
include_once 'config.php';
include 'ChromePhp.php';
//Receive the RAW post data via the php://input IO stream.
$content = file_get_contents("php://input");
$email = $_POST["email"];
$text= $_POST["text"];
if(strpos($text, "\n") !== FALSE) {
$text = str_replace("\n", "<br>", $text);
}
$replace_to_standard=[$name, $text];
$replace_standard =['nametochange', 'textochange'];
$delivery_added = str_replace($replace_standard, $replace_to_standard, file_get_contents('standardMail.html'));
echo "" . $delivery_added . "";
$m = new MailSender;
$m-> sendMail($email, $email, $delivery_added, "Mail All");

Jquery error: Uncaught TypeError: Cannot read property 'length' of undefined

I have a form to call ajax for back-end processing, all input will stored in table and will return 'success' to to notify user the submission is success. But I facing an issue during callback, input data can saved into table but the callback is halted with error below, I have no idea what is goes wrong, the same script was applied to another form (with different form field) are working fine.
console log - Chrome:
Uncaught TypeError: Cannot read property 'length' of undefined
m.extend.each
$.ajax.success
j
k.fireWith
x
b
Firefox
TypeError: a is undefined
...rCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e...
firefox error is pointed to f=a.
Script:
$(document).ready(function() {
$("#status").hide();
$('#btn_submit').click(function(){
var params = $('#project_form').serialize();
var btn = $(this);
btn.button('loading')
$.ajax({
url: baseurl + '/process_form.php',
type: 'POST',
data: params,
dataType: 'json',
success: function(response){
if(response.success == 'success'){
$('#status').html('<b>Thank you</b>').show();
$('html,body').animate({
scrollTop: $('#top').offset().top
},500);
}else{
$('[id$="_error"]').html('');
$.each(response.error, function(key, value){
if(value){
$('#' + key + '_error').html(value);
}
});
}
},
error: function(){
console.log(arguments);
}
}).always(function(){
btn.button('reset')
});
});
});
process_form.php
header("Content-Type: application/json");
$serialized_data = serialize($_POST);
$fullname = $mysqli->real_escape_string(ucwords(strtolower($_POST['fullname'])));
$age = $mysqli->real_escape_string(ucwords(strtolower($_POST['age'])));
$email = $mysqli->real_escape_string(strtolower(trim($_POST['semail'])));
$phone = $mysqli->real_escape_string(trim($_POST['phone']));
$proj_id = preg_replace('/[^0-9]/', '', $mysqli->real_escape_string($_POST['project_id']));
$proj_name = $mysqli->real_escape_string(ucwords(strtolower($_POST['project_name'])));
$agent_id = preg_replace('/[^0-9]/', '', $mysqli->real_escape_string($_POST['agent_id']));
$agent_email = $mysqli->real_escape_string(strtolower(trim($_POST['agent_email'])));
$agent_name = $mysqli->real_escape_string(ucwords(strtolower($_POST['agent_name'])));
$captcha = $_POST['captcha_code'];
$func = new Functions();
$message = array();
// validate
if(empty($fullname) || strlen($fullname) < 2){
$message['error']['fullname'] = 'Your name is required';
}
if(empty($age)){
$message['error']['age'] = 'Your age is required';
}
if(!$func->check_email_address($email)){
$message['error']['semail'] = 'Invalid email address';
}
if(empty($phone) || strlen($phone) < 10){
$message['error']['phone'] = 'Phone num is required';
}
$securimage = new Securimage();
$securecode = $securimage->getCode();
if(strtolower($securecode) != strtolower($captcha)) {
$message['error']['captcha'] = 'Incorrect security code';
}
if(!isset($message['error'])){
// insert table
$create = $mysqli->query("INSERT INTO `xxx` ...") or die($mysqli->error);
if($create){
//send email
$to = xxx;
$subject = 'yyy';
$msg = '<html>
<body>
blah...
</body>
</html>';
$from = zzz;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
$headers .= 'From: '.$fullname.' <'.$from.'>' . "\r\n";
if(mail($to, $subject, $msg, $headers)){
$message['success'] = 'success';
}
}
}
echo json_encode($message);
change this:
if(response.success == 'success'){
to this:
if(response[0].success == 'success'){
What seems to me, you have an array of object [{}] so response.success is not available that way, instead you can pass the index like suggested in the answer above response[0].success.
I think it is because the mail function failed, and returned false here:
if(mail($to, $subject, $msg, $headers)){
$message['success'] = 'success';
}
so your response neither has success property, nor error property, and this causes an error here:
$.each(response.error, function(key, value){
if(value){
$('#' + key + '_error').html(value);
}
});
You can try something like:
if(mail($to, $subject, $msg, $headers)){
$message['success'] = 'success';
}else{
$message['error']['mail'] = 'Mail error!';
}
or set $message['success'] = 'success'; directly after saving data into table regardless mail success.

Contact form doesn't transfer data from AngularJS to PHP

I am trying to retrieve data from AngularJS file to PHP file, but I get the error that it's empty.
I can't find any good examples that are dealing with posting data from angularJS to php file and so I need help.
Angularjs file:
angular.module('myApp', ['ajoslin.promise-tracker'])
.controller('help', function ($scope, $http, $log, promiseTracker, $timeout) {
$scope.ph_numbr =/[0-9]+/;
// Form submit handler.
$scope.submit = function(form) {
// Trigger validation flag.
$scope.submitted = true;
// If form is invalid, return and let AngularJS show validation errors.
if (!$scope.toggle || $scope.toggle.length <= 0 || form.$invalid) {
return;
}
// Default values for the request.
$scope.progress = promiseTracker('progress');
var config = {
params : {
//'callback' : 'JSON_CALLBACK',
'name' : $scope.name,
'email' : $scope.email,
'toggle' : $scope.toggle,
'phone' : $scope.phone,
'comments' : $scope.comments
},
tracker : 'progress'
};
$http({
method : 'POST',
url : 'js/contact.php',
data: config,
headers : {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})
.success(function(data, status, headers, config) {
if (data.success) {
$scope.name = null;
$scope.email = null;
$scope.toggle = null;
$scope.phone = null;
$scope.comments = null;
$scope.messages = 'Your form has been sent!';
$scope.submitted = false;
} else {
$scope.messages = 'Oops, we received your request, but there was an error processing it.';
$log.error(data);
}
})
.error(function(data, status, headers, config) {
$scope.progress = data;
$scope.messages = 'There was a network error. Try again later.';
$log.error(data);
});
// Hide the status message which was set above after 3 seconds.
var promise = $timeout(function() {
$scope.messages = null;
}, 3000);
$scope.progress.addPromise(promise);
};
});
php file:
<?php
/*error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'js/PHPMailerAutoload.php';*/
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
$data = file_get_contents("php://input");
$postData = json_decode($data);
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['toggle']) && isset($_POST['comments'])) {
//check if any of the inputs are empty
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['toggle']) || empty($_POST['comments'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
$email = trim($_POST['email']);
$subject = trim($_POST['toggle']);
//email address settings
$my_address = "*#yahoo.com";
$headers = "From: ".$email;
$message = "Name: " . $_POST['name'] . "\r\n\r\nMessage: " . $_POST["phone"] . "\r\n\r\nMessage: " . stripslashes($_POST['comments']);
$to = $my_address;
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
mail($to, $subject, $message, $headers);
$data = array('success' => true, 'message' => 'Thanks! We have received your message.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
}
?>
The error message that I get is: "Please fill out the form completely" - which means it doesn't get the values.
My other question is how in the AngularJS do I retrieve the data.success value from the php file?
You seem to be getting the data here:
$data = file_get_contents("php://input");
$postData = json_decode($data);
but then you're using $_POST instead. Perhaps this would work:
if (empty($postData['name']) //etc
It looks like you're accessing data.success appropriately and the value should be set to false as your code currently is.
Additional code review:
If there are errors on the server, it's best to return a status code that indicates that. As is, the server is returning 200 (default), which means everything is OK, even though the request is actually failing. That would eliminate the need for data.success. If the server sends status 200, your .success function will fire. If it returns an error status, like 404, then your .error function would fire instead.
I have doubts about your need of the Content-Type header. You might want to reconsider if that's necessary.
On your Angular form, you ought to nest those $scope properties in an object:
$scope.formData = {
name: '',
email: '',
//etc
}
Then, you can simply pass that directly to your $http call and to reset the values you can simply do $scope.formData = {}.

Google Apps Script send post request to phpMailer using UrlFetchApp

I would like to send data with UrlFetchApp but something is not working. I not understand where is the problem are not very experienced in question, can someone explain to me how to configure both files to send and receive parameters?
Google Apps Script:
function sendEXTmail(name,email,subject,body) {
var url = "http://www.mysite.com/willy.php";
var options = {
"method": "post",
"payload": {
"From_Name": "Fix Name",
"From_Email": "fix_mail#domain.com",
"To_Name": name,
"To_Email": email,
"Subject": subject,
"Message": body
}
};
var response = UrlFetchApp.fetch(url, options);
return response;
}
PHP:
require "phpmailer/class.phpmailer.php";
$from_name = (isset($_POST['From_Name'])) ? $_POST['From_Name'] : '';
$from_email = (isset($_POST['From_Email'])) ? $_POST['From_Email'] : '';
$to_name = (isset($_POST['To_Name'])) ? $_POST['To_Name'] : '';
$to_email = (isset($_POST['To_Email'])) ? $_POST['To_Email'] : '';
$subject = (isset($_POST['Subject'])) ? $_POST['Subject'] : '';
$message = (isset($_POST['Message'])) ? $_POST['Message'] : '';
$mail= new PHPmailer();
$mail->IsSMTP();
$mail->IsHTML(true);
$mail->Host = "localhost";
$mail->Port = 25;
$mail->SMTPSecure = "none";
$mail->SMTPAuth = false;
$mail->addReplyTo($from_email, $from_name);
$mail->From = $from_email;
$mail->FromName = $from_name;
$mail->addAddress($to_email, $to_name);
$mail->Subject = $subject;
$mail->Body = '<html>'.$message.'</html>';
if(!$mail->Send()){
echo $mail->ErrorInfo;
}else{
echo 'Email inviata correttamente!';
}
$mail->SmtpClose();
unset($mail);
?>
On the Google Apps Script side, you can review the message to be sent by using UrlFetchApp.getRequest(). For example:
// Log readable JSON object
Logger.log(
JSON.stringify(
UrlFetchApp.getRequest(url,options),
null, 2 ));
Here's what it logs:
[15-05-06 22:23:35:144 EDT] {
"headers": {
"X-Forwarded-For": "99.224.168.137"
},
"useIntranet": false,
"followRedirects": true,
"payload": "From_Name=Fix+Name&Subject=subject_param&Message=body&From_Email=fix_mail#domain.com&To_Email=email#example.com&To_Name=name_param",
"method": "post",
"contentType": "application/x-www-form-urlencoded",
"validateHttpsCertificates": true,
"url": "http://www.example.com/willy.php"
}
Based on that, it appears that your function has prepared a POST request that should match your PHP.
Next, check the result of the POST itself. To that, first use the muteHttpExceptions option, then look for and handle the return code in your function by using HttpResponse.getResponseCode(). Furthermore, to obtain the readable text from the response, use response.getContentText(). Here's how that might look:
function sendEXTmail(name,email,subject,body) {
name = name || "name_param";
email = email || "email#example.com";
subject = subject || "subject_param";
body = body || "body";
var url = "http://www.example.com/willy.php";
var options = {
"muteHttpExceptions": true,
"method": "post",
"payload": {
"From_Name": "Fix Name",
"From_Email": "fix_mail#domain.com",
"To_Name": name,
"To_Email": email,
"Subject": subject,
"Message": body
}
};
// Log readable JSON object
Logger.log(
JSON.stringify(
UrlFetchApp.getRequest(url,options),
null, 2 ));
var response = UrlFetchApp.fetch(url, options);
var rc = response.getResponseCode();
if (rc !== 200) {
// Failure - log it
Logger.log( "Error %s: %s", rc, response.getContentText())
}
return response.getContentText();
}
Try this with your real URL, and see what you get back. If it's a 200, then the Google Apps Script side of the exchange has worked properly. If not, the response should tell you more about the nature of the failure, and help you along to a solution.

Categories