Google Apps Script send post request to phpMailer using UrlFetchApp - php

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.

Related

Checkbox is throwing an error in a PHP form

I've got a script that I downloaded that's a contact form with reCaptcha v3 which emails the filled out form.
The reCaptcha and mail is working, but am having a problem with the checkboxes.
When I fill out the form, my error log says
PHP Warning: Undefined variable $instype in /home1/bluehqwi/public_html/gowithfm/quote/AjaxForm.php on line 121
The code at line 121 is:
'instype[]' => $instype
This is what I have in the AjaxForm.php for checkboxes -
if(!empty($_POST['instype[]'])) {
foreach($_POST['instype[]'] as $instype){
echo "value : ".$instype.'<br/>';
}
}
In my form, my checkboxes are -
<input class="form-check-input shadow-none" type="checkbox" value="Business insurance" name="instype[]" id="instype">
<label class="form-check-label" for="instype">Business insurance</label>
<input class="form-check-input shadow-none" type="checkbox" value="Life insurance" name="instype[]" id="instype">
<label class="form-check-label" for="instype">Life insurance</label>
I need to have multiple checkboxes in the contact form and have those displayed in the email that's sent.
I'm more on the UX/UI Design side, so I'm not really fluent in Ajax and PHP, so any help is appreciated.
Thanks!
NOTE: Here's the complete AjaxForm.php file.
<?php
/**
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
# https://www.php.net/manual/fr/timezones.php
date_default_timezone_set('America/Los_Angeles');
require __DIR__ . '/../PHPMailer/Exception.php';
require __DIR__ . '/../PHPMailer/PHPMailer.php';
require __DIR__ . '/../PHPMailer/SMTP.php';
require __DIR__ . '/../recaptcha/autoload.php';
class Ajax_Form {
# Constants to redefined
# Check this for more configurations: https://blog.mailtrap.io/phpmailer
const HOST = 'xxxxx'; # SMTP server
const USERNAME = 'xxxxx'; # SMTP username
const PASSWORD = 'xxxxx'; # SMTP password
const SECRET_KEY = 'xxxxx'; # GOOGLE secret key
const SMTP_SECURE = PHPMailer::ENCRYPTION_STARTTLS;
const SMTP_AUTH = true;
const PORT = 587;
const SUBJECT = 'xxxxx';
const HANDLER_MSG = [
'success' => '✔️ Your message has been sent !',
'token-error' => '❌ Error recaptcha token.',
'enter_firstname' => '❌ Please enter your first name.',
'enter_lastname' => '❌ Please enter your last name.',
'enter_email' => '❌ Please enter a valid email.',
'enter_phone' => '❌ Please enter a valid phone number.',
'enter_message' => '❌ Please enter your message.',
'enter_instype' => '❌ Please enter instype.',
'bad_ip' => '❌ 56k ?',
'ajax_only' => '❌ Asynchronous anonymous.',
'email_body' => '
<h1>{{subject}}</h1>
<p><b>First name:</b> {{firstname}}</p>
<p><b>Last name:</b> {{lastname}}</p>
<p><b>Email:</b> {{email}}</p>
<p><b>Phone:</b> {{phone}}</p>
<p><b>Address 1:</b> {{address1}}</p>
<p><b>Address 2:</b> {{address2}}</p>
<p><b>City:</b> {{city}}</p>
<p><b>State:</b> {{state}}</p>
<p><b>Zip:</b> {{zip}}</p>
<p><b>Interested in:</b> {{instype}}</p>
'
];
/* <p><b>Date</b>: {{date}}</p>
<p><b>Name</b>: {{name}}</p>
<p><b>E-Mail</b>: {{email}}</p>
<p><b>Message</b>: {{message}}</p>
<p><b>IP</b>: {{ip}}</p>
'
];*/
/**
* Ajax_Form constructor
*/
public function __construct()
{
# Check if request is Ajax request
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] !== 'XMLHttpRequest') {
$this->statusHandler('ajax_only');
}
# Check if fields has been entered and valid
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$firstname = $this->secure($_POST['firstname']) ?? $this->statusHandler('enter_name');
$lastname = $this->secure($_POST['firstname']) ?? $this->statusHandler('enter_name');
$email = filter_var($this->secure($_POST['email']), FILTER_SANITIZE_EMAIL) ?? $this->statusHandler('enter_email');
$phone = $this->secure($_POST['phone']) ?? $this->statusHandler('enter_phone');
$address1 = $this->secure($_POST['address1']) ?? $this->statusHandler('enter_address1');
$address2 = $this->secure($_POST['address2']) ?? $this->statusHandler('enter_address2');
$city = $this->secure($_POST['city']) ?? $this->statusHandler('enter_city');
$state = $this->secure($_POST['state']) ?? $this->statusHandler('enter_state');
$zip = $this->secure($_POST['zip']) ?? $this->statusHandler('enter_zip');
# if (!empty($_POST['instype']))
# $instype = $this->secure($_POST['instype']);
# else
# $this->statusHandler('enter_instype');
if(!empty($_POST['instype'])) {
foreach($_POST['instype'] as $instype){
echo "value : ".$instype.'<br/>';
}
}
# $message = $this->secure($_POST['message']) ?? $this->statusHandler('enter_message');
$token = $this->secure($_POST['recaptcha-token']) ?? $this->statusHandler('token-error');
$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP) ?? $this->statusHandler('bad_ip');
$date = new DateTime();
}
# Prepare email body
$email_body = self::HANDLER_MSG['email_body'];
$email_body = $this->template($email_body, [
'subject' => self::SUBJECT,
'date' => $date->format('j/m/Y H:i:s'),
'firstname' => $firstname,
'lastname' => $lastname,
'email' => $email,
'phone' => $phone,
'address1' => $address1,
'address2' => $address2,
'city' => $city,
'state' => $state,
'zip' => $zip,
'instype' => $instype
]);
# Verifying the user's response
$recaptcha = new \ReCaptcha\ReCaptcha(self::SECRET_KEY);
$resp = $recaptcha
->setExpectedHostname($_SERVER['SERVER_NAME'])
->verify($token, $_SERVER['REMOTE_ADDR']);
if ($resp->isSuccess()) {
# Instanciation of PHPMailer
$mail = new PHPMailer(true);
$mail->setLanguage('en', __DIR__ . '/vendor/PHPMailer/language/');
try {
# Server settings
$mail->SMTPDebug = SMTP::DEBUG_OFF; # Enable verbose debug output
$mail->isSMTP(); # Set mailer to use SMTP
$mail->Host = self::HOST; # Specify main and backup SMTP servers
$mail->SMTPAuth = self::SMTP_AUTH; # Enable SMTP authentication
$mail->Username = self::USERNAME; # SMTP username
$mail->Password = self::PASSWORD; # SMTP password
$mail->SMTPSecure = self::SMTP_SECURE; # Enable TLS encryption, `ssl` also accepted
$mail->Port = self::PORT; # TCP port
# Recipients
$mail->setFrom(self::USERNAME, $firstname, $lastname);
$mail->addAddress($email, $firstname, $lastname);
$mail->AddCC(self::USERNAME, 'Dev_copy');
$mail->addReplyTo(self::USERNAME, 'Information');
# Content
$mail->isHTML(true);
$mail->CharSet = 'UTF-8';
$mail->Subject = self::SUBJECT;
$mail->Body = $email_body;
$mail->AltBody = strip_tags($email_body);
# Send email
$mail->send();
$this->statusHandler('success');
} catch (Exception $e) {
die(json_encode($mail->ErrorInfo));
}
} else {
die(json_encode($resp->getErrorCodes()));
}
}
/**
* Template string values
*
* #param string $string
* #param array $vars
* #return string
*/
public function template(string $string, array $vars): string
{
foreach ($vars as $name => $val) {
$string = str_replace("{{{$name}}}", $val, $string);
}
return $string;
}
/**
* Secure inputs fields
*
* #param string $post
* #return string
*/
public function secure(string $post): string
{
$post = htmlspecialchars($post, ENT_QUOTES);
$post = stripslashes($post);
$post = trim($post);
return $post;
}
/**
* Error or success message
*
* #param string $message
* #return json
*/
public function statusHandler(string $message): json
{
die(json_encode(self::HANDLER_MSG[$message]));
}
}
# Instance
new Ajax_Form();
Here's the AjaxForm.js code
const publicKey = "XXXXX"; // GOOGLE public key
// Get token from API
function check_grecaptcha() {
grecaptcha.ready(function () {
grecaptcha.execute(publicKey, {
action: "ajaxForm"
}).then(function (token) {
$("[name='recaptcha-token']").val(token);
});
});
}
// Show response in .alert
function alertShowing(response) {
$("#response-alert").html(JSON.parse(response));
$("#response-alert").removeClass("d-none");
$("#response-alert").addClass("d-block");
}
$(function () {
check_grecaptcha();
$("#contactform").validate({
// Form fields rules
rules: {
firstname: {
required: true,
minlength: 3
},
lastname: {
required: true,
minlength: 3
},
email: {
required: true,
email: true
},
message: {
required: false,
minlength: 5
}
},
// Error messages
messages: {
firstname: {
required: "Please enter your first name.",
minlength: "Must be at least 3 characters long."
},
lastname: {
required: "Please enter your last name.",
minlength: "Must be at least 3 characters long."
},
email: "Please enter a valid email.",
message: {
required: "Please enter your message.",
minlength: "Must be at least 5 characters long."
}
},
errorClass: "invalid-feedback",
// Dynamic validation classes
highlight: function (element) {
$(element).addClass("is-invalid").removeClass("is-valid");
},
unhighlight: function (element) {
$(element).addClass("is-valid").removeClass("is-invalid");
},
// Action on submit
submitHandler: function (form) {
$(".spinner-border").removeClass("d-none");
$("#sendtext").addClass("d-none");
$.post(form.action, $(form).serialize())
.done(function (response) {
alertShowing((response));
$(".spinner-border").addClass("d-none");
$("#sendtext").removeClass("d-none");
$("#submit-btn").prop("disabled", true);
check_grecaptcha();
setTimeout(function () {
$("#submit-btn").prop("disabled", false);
$("form").trigger("reset");
$("form").each(function () {
$(this).find(".form-control").removeClass("is-valid")
})
}, 3000);
})
.fail(function (response) {
alertShowing((response));
$(".spinner-border").addClass("d-none");
$("#sendtext").removeClass("d-none");
});
}
});
});
Like already stated in the comments. You never initialized your variable $instype, but you try to access it several times. At least inititialize the variable before any access with an empty value like
$instype = ''
or by uncommenting
$instype = $this->secure($_POST['instype']);
But be aware, this won't solve your problem since you have this line in a comment and also will never be run if the the if-condition does not match.

Contact form submits regardless of Recaptcha - suspecting ajax validator

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()) {

Xcode 8 Swift 3.0 : Parse error - Could not read PHPMailer code

I have a problem on xcode 8.
In PHP, I'm using PHPMailer to send the email. my PHP code like below.
send.php
<?php
require 'database/connect.php';
global $connect;
date_default_timezone_set('Etc/UTC');
require 'PHPMailer-master2/PHPMailerAutoload.php';
if ( isset($_POST['data1']) && isset($_POST['data2']))
{
$data1 = $_POST['data1'];
$data2 = $_POST['data2'];
$sql = "SELECT * FROM table WHERE data1 = '$data1' AND data2='$data2'";
$result = mysqli_query($connect, $sql);
if ($result && mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_array($result)){
}
$output = array('message' => '1');
echo json_encode($output);
$add = "INSERT INTO table (data1, data2)
VALUES ('$data1','$data2')
";
$run = mysqli_query($connect,$add);
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'gmail.com';
$mail->Password = '******';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('sender#mail.com', 'sender');
$mail->addAddress('receiver#mail.com','receiver');
$mail->isHTML(true);
$mail->Subject = 'Test';
$mail->Body = 'Test';
$mail->AltBody = 'Test';
if(!$mail->send()) {
echo json_encode([
'status' => false,
'message' => 'Message could not be sent. Error: ' . $mail->ErrorInfo
]);
} else {
$status = array();
$status[] = array('status' => '1');
}
$output = array('message' => '1', 'status' => $status);
echo json_encode($output);
exit();
// End sending email
exit();
mysqli_free_result($result);
}
else {}
}
?>
I managed to send the data to the server and send email to receiver using code above.
The only issue I'm facing right now is in xcode. It says:
Parse error: The data couldn’t be read because it isn’t in the correct
format.
Xcode can't read my PHPMailer code in PHP file, that cause my swift 3.0 code to execute an Catch statement instead of message == '1' statement. My swift code as below.
post.swift
#IBAction func sendApplyMovement(_ sender: Any) {
let url = URL(string: "http://localhost/send.php")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"
let valueToSend = "data1=&data2"
request.httpBody = valueToSend.data(using: String.Encoding.utf8)
let myAlert = UIAlertController(title: "Confirm", message: "Sure ?", preferredStyle: UIAlertControllerStyle.alert)
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil)
let okaction = UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler:
{
action in
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
if error != nil {
return
}
else {
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [String: String]
{
DispatchQueue.main.async {
let message = Int(json["message"]!)
let status = Int(json["status"]!)
if(message == 1){
if(status == 1){
print("Success")
let myViewController:ViewController = self.storyboard!.instantiateViewController(withIdentifier: "ViewController") as! ViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let navigationController = UINavigationController.init(rootViewController: myViewController)
appDelegate.window?.rootViewController = navigationController
appDelegate.window?.makeKeyAndVisible()
let myAlert = UIAlertController(title: "Success!", message: "Sent !", preferredStyle: UIAlertControllerStyle.alert)
myAlert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil))
navigationController.present(myAlert, animated: true, completion: nil)
return
}
}
else {return}
}
}
}
catch let parseError { print("Parse error: \(parseError.localizedDescription)") }
}
})
task.resume()
}
)
myAlert.addAction(okaction)
myAlert.addAction(cancel)
self.present(myAlert, animated: true, completion: nil)
}
}
Is there something that I need to modify in order to make it work?
You're doing this:
if let json = try JSONSerialization.jsonObject(with: data!)
This implies that the data you're getting is in JSON format, but your PHPMailer code does this:
if(!$mail->send())
{
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else
{
echo 'Message has been sent';
}
which does not return JSON code, so I'm not surprised you're having trouble parsing it. You posted this question before but it was very unclear - you made it sound like Xcode couldn't open your PHP file, not that you couldn't parse a response; it's a Swift runtime error, not an Xcode error.
Return your response in JSON format and you might have more success, something like:
if(!$mail->send()) {
echo json_encode([
'status' => false,
'message' => 'Message could not be sent. Error: ' . $mail->ErrorInfo
]);
} else {
echo json_encode([
'status' => true,
'message' => 'Message sent'
]);
}

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 = {}.

EWS - php sending email with attachment

I'm new to using EWS from Exchangeclient classes.
I'm looking for a simple example how to send an email with an attachment. I've found examples about how to send an email but not sending an email with an attachment.
This is my script:
$exchangeclient = new Exchangeclient();
$exchangeclient->init($username, $password, NULL, 'ews/Services.wsdl');
$exchangeclient->send_message($mail_from, $subject, $body, 'HTML', true, true);
function - PHP Classes:
function send_message($to, $subject, $content, $bodytype="Text", $saveinsent=true, $markasread=true) {
$this->setup();
if($saveinsent) {
$CreateItem->MessageDisposition = "SendOnly";
$CreateItem->SavedItemFolderId->DistinguishedFolderId->Id = "sentitems";
}
else
$CreateItem->MessageDisposition = "SendOnly";
$CreateItem->Items->Message->ItemClass = "IPM.Note";
$CreateItem->Items->Message->Subject = $subject;
$CreateItem->Items->Message->Body->BodyType = $bodytype;
$CreateItem->Items->Message->Body->_ = $content;
$CreateItem->Items->Message->ToRecipients->Mailbox->EmailAddress = $to;
if($markasread)
$CreateItem->Items->Message->IsRead = "true";
$response = $this->client->CreateItem($CreateItem);
$this->teardown();
if($response->ResponseMessages->CreateItemResponseMessage->ResponseCode == "NoError")
return true;
else {
$this->lastError = $response->ResponseMessages->CreateItemResponseMessage->ResponseCode;
return false;
}
}
You have to first save the email as a draft (with the appropriate message disposition), then CreateAttachment() so it has an attachment, then edit it with UpdateItem() so the message disposition is SendOnly. Then it will be sent.
See David Sterling's reply on this thread: http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/f7d5257e-ec98-40fd-b301-f378ba3080fd/ (It's about Meeting Requests but they work the same way.)

Categories