Can't send Email using PhP - javascript

I am trying to send an email from a form using php ,here is my PHP code(along with the validation ,didn't want to leave anything out :_)
<?php
/*
* Contact Form Class
*/
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$admin_email = 'sgg3590#rit.edu'; // Your Email
$message_min_length = 5; // Min Message Length
class Contact_Form{
function __construct($details, $email_admin, $message_min_length){
$this->name = stripslashes($details['name']);
$this->email = trim($details['email']);
$this->subject = 'Contact from Your Website'; // Subject
$this->message = stripslashes($details['message']);
$this->email_admin = $email_admin;
$this->message_min_length = $message_min_length;
$this->response_status = 1;
$this->response_html = '';
}
private function validateEmail(){
$regex = '/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';
if($this->email == '') {
return false;
} else {
$string = preg_replace($regex, '', $this->email);
}
return empty($string) ? true : false;
}
private function validateFields(){
if(!$this->name)
{
$this->response_html .= '<p>Please enter your name</p>';
$this->response_status = 0;
}
// Check email
if(!$this->email)
{
$this->response_html .= '<p>Please enter an e-mail address</p>';
$this->response_status = 0;
}
// Check valid email
if($this->email && !$this->validateEmail())
{
$this->response_html .= '<p>Please enter a valid e-mail address</p>';
$this->response_status = 0;
}
// Check message length
if(!$this->message || strlen($this->message) < $this->message_min_length)
{
$this->response_html .= '<p>Please enter your message. It should have at least '.$this->message_min_length.' characters</p>';
$this->response_status = 0;
}
}
private function sendEmail(){
$mail = mail($this->email_admin, $this->subject, $this->message,
"From: ".$this->name." <".$this->email.">\r\n"
."Reply-To: ".$this->email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
$this->response_status = 1;
$this->response_html = '<p>Thank You!</p>';
}
else
{
$this->response_status = 0;
$this->response_html = '<p>Sending failed</p>';
}
}
function sendRequest(){
$this->validateFields();
if($this->response_status)
{
$this->sendEmail();
}
$response = array();
$response['status'] = $this->response_status;
$response['html'] = $this->response_html;
echo json_encode($response);
}
}
$contact_form = new Contact_Form($_POST, $admin_email, $message_min_length);
$contact_form->sendRequest();
?>
here is how I am calling it
BRUSHED.contactForm = function(){
$("#contact-submit").on('click',function() {
$contact_form = $('#contact-form');
var fields = $contact_form.serialize();
$.ajax({
type: "POST",
url: "_include/php/contact.php",
data: fields,
dataType: 'json',
success: function(response) {
if(response.status){
$('#contact-form input').val('');
$('#contact-form textarea').val('');
}
$('#response').empty().html(response.html);
}
});
return false;
});
}
And here is my form
<form id="contact-form" class="contact-form" action="#">
<p class="contact-name">
<input id="contact_name" type="text" placeholder="Full Name" value="" name="name" />
</p>
<p class="contact-email">
<input id="contact_email" type="text" placeholder="Email Address" value="" name="email" />
</p>
<p class="contact-message">
<textarea id="contact_message" placeholder="Your Message" name="message" rows="5" cols="40"></textarea>
</p>
<p class="contact-submit">
<a id="contact-submit" class="submit" href="#">Send Your Email</a>
</p>
<div id="response">
</div>
</form>
The validations work proper so its going to the php file, but I can't send the email and the response div is not fill after I push the send button(neither with thank you or sending fail)
I followed this code from a website and I Don't really understand whats wrong here.. :(

First make sure you have set your machine host same as domain name, as sometimes mail-servers will deny mail-headers that doesn't have matching domain, like Sender: test#test.org but From: localhost.
Then, install postfix so it will correct any improper / incorrect stuff in the email and lastly, you're missing email headers there. Here are my example that works for me:
<?php
try {
$to = 'user#test.org';
$subject = 'Mail Test';
$message = <<<TEXT
Mail request received
TEXT;
$message = str_replace("\n.", "\n..", $message);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: Test Org. <webmaster#test.org>' . "\r\n" .
'Reply-To: webmaster#test.org' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
printf("Mail sent to " + $to);
} catch (Exception $e) {
printf("Error occured: " + $e);
}
?>
If it still fails, you can try sending a test message from console echo "this is the body" | mail -s "test" "receipent#test.org" and see if it works. If both failed, best to ask server vendor as maybe they have set outgoing mail disabled or something.

Well I was using local host with WAMP and realized wamp server doesn't provide the functionality . THe code is good and working though.
Thanks

Related

How can I use reCAPTCHA with my form contact?

When I press button Submit on form, reCAPTCHA will allow.
My form can send message without check I'm not a robot.
I don't know if it's about include ajax.
How can I use reCAPTCHA with my form contact?
Thank you very much for your time and assistance in this matter.
This my HTML code.
<form class="callus" onSubmit="return false">
<div id="result"></div>
<input type="text" name="name" id="name">
<input type="email" name="email" id="email">
<textarea name="message" id="message"></textarea>
<div class="g-recaptcha" data-sitekey="XXXXX"></div>
<button id="submit_btn">Submit</button>
</form>
This is my Javascript.
jQuery(document).ready(function($){
$("#submit_btn").click(function() {
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email]').val();
var user_message = $('textarea[name=message]').val();
var post_data, output;
var proceed = true;
if(user_name==""){
proceed = false;
}
if(user_email==""){
proceed = false;
}
if(user_subject==""){
proceed = false;
}
if(user_message==""){
proceed = false;
}
if(proceed) {
post_data = {'userName':user_name, 'userEmail':user_email, 'userMessage':user_message};
$.post('email.php', post_data, function(response){
if(response.type == 'error') {
output = '<div class="alert-danger">'+response.text+'</div>';
}else{
output = '<div class="alert-success">'+response.text+'</div>';
$('.callus input').val('');
$('.callus textarea').val('');
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
$(".callus input, .callus textarea").keyup(function() {
$("#result").slideUp();
});
});
email.php
<?php
if($_POST) {
$to_Email = 'demo#localhost.com';
$subject = 'New Contact Inquiry';
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"])) {
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
die($output);
}
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
if(strlen($user_Name)<3) {
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) {
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($user_Message)<5) {
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
$message_Body = "<strong>Name: </strong>". $user_Name ."<br>";
$message_Body .= "<strong>Email: </strong>". $user_Email ."<br>";
$message_Body .= "<strong>Message: </strong>". $user_Message ."<br>";
$headers = "From: " . strip_tags($user_Email) . "\r\n";
$headers .= "Reply-To: ". strip_tags($user_Email) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$sentMail = #mail($to_Email, $subject, $message_Body, $headers);
if(!$sentMail) {
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for contacting us.'));
die($output);
}
}
?>
You have to validate captcha code at server side . Once you checked captcha it will give you captcha code.
var captchaCode = this.grecaptcha.getResponse();
Re-Captcaha provide callback functions like
<div class="g-recaptcha" id="headerCaptcha" data-callback="recaptchaCallbackHeader" data-expired-callback="recaptchaExpiryHeader" data-sitekey="xxx"></div>
You have to post this capthca code to backednd for validation inside recaptchaCallbackHeader. (refer below links for detail code)
$secretKey = "Put your secret key here";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
Inresponse of this API you will get .
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo '<h2>You are not a robot #$%K out</h2>';
} else {
echo '<h2>Thanks for posting comment.</h2>';
}
Remember recaptcha provide two types of keys.
Private key which is used on server side for validation of captcha code.
Site-key which is used to render captcha on clint side.
See how reCaptcah works
And Here to validate using PHP.

How to Redirect PHP form with Javascript depending on echo

I'm looking for a way to redirect after submit depending on the echo
and i used the following code:
<?php
$to = "mymail#gmail.com";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$subject = "New Client Call";
$body = 'name: ' .$name."\r\n";
$body = 'email: ' .$email."\r\n";
$body = 'message: ' .$message."\r\n";
$go = mail($to, $subject, $body, "From:<$email>");
if ($go) {
echo "Success";
}
else {
echo "error";
}
?>
<form action="index9.html" method="post" name="redirect" ></form>
<script> document.forms['redirect'].submit()</script>
but i have now two problems:
i am always getting "success" echo. even the client sending empty details.
i want to redirect to an error page with Javascript (if/else) and i don't now how.
BTW i am new in this field so:
I will appreciate your advise/help and be thankful.
You don't need javascript to achive this you can use pure php.
You can use error checking if a field is empty in the form as follows
validate.php
if(isset($_POST['submit'])){
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (isset( $nameErr) || isset($emailErr){
// you have a error
}
else {
$to = "mymail#gmail.com";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$subject = "New Client Call";
....
This will check if "email" field is empty if it is it will promp a error "Email is required"
And then in your html you add the error
<form class="form-horizontal" action="validate.php" method="post">
<label for="email">Email: </label>
<input type="text" class="form-control input-sm" name="email">
<span class="error">* <br><?php echo $emailErr;?></span>
<input class="btn btn-info btn-lg" type="submit" name="submit" value="Submit">
</form>
Hope that helps
You seem to be on the right path, before throwing the arguments into the the mailer I would say you can do more sanity checking to make sure all values are entered, this way you avoid trying to send emails that you know will fail, so you fail early and notify the user, you may also see the error message the mail function returns in case of failure to make it easy to rectify any other issues by using the erorr_get_last() method.
echo error_get_last()['message'];
Note: php mail does not verify the headers given, so you have to be 100% sure it's clean and there are no possibilities for the user to inject their own headers, so make sure you sanitize that too.
Then to do redirecting you can just directly replace the echo "success" and echo "error" calls with your javascript part.
So the script would finally look like this:
<?php
$to = "mymail#gmail.com";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$subject = "New Client Call";
$missingFieldCount = 0;
if(!isset($_POST['name'])) {
echo "Error: Name requried";
$missingFieldCount++;
}
if(!isset($_POST['email'])) {
echo "Error: Email required";
$missingFieldCount++;
}
if(!isset($_POST['message'])) {
echo "Error: message required";
$missingFieldCount++;
}
if($missingFieldcount > 0) {
echo "Please fill in the missing $missingFieldcount fields, then submit again";
} else {
$body = 'name: ' .$name."\r\n";
$body .= 'email: ' .$email."\r\n"; // Using .= to append instead of replace
$body .= 'message: ' .$message."\r\n";
$headers = "From:<$email>"; //Make sure $email is actually just an email address and not injected headers
$success = mail($to, $subject, $body, $headears);
if ($success) {
$redirectPage = "successPage.html"
} else {
$redirectPage = "errorPage.html"
echo "An error occured:";
//Don't show this to the user, but log it to file instead
//this is here only for demonstration
echo error_get_last()['message'];
}
echo "<form action="$redirectPage" method="post" name="redirect" ></form>";
echo "<script> document.forms['redirect'].submit()</script>";
}
}
?>
Tnq Guys for your answers.
finally i manged a perfect PHP form from all the information i get in this issue. no need Javascript to redirect TO 2 different pages:
1. Thank you page.
2. error page.
and the code is like this:
<?php
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$to = "mymail#gmail.com";
$subject = " New Client order ";
$errors = 0;
$body ="";
$body .="Name: ";
$body .=$name;
$body .="\n";
$body .="Email: ";
$body .=$email;
$body .="\n";
$body .="Message: ";
$body .=$message;
$body .="\n";
if(isset($_POST['submit'])) { // Checking null values in message.
$name = $_POST["name"]; // Sender Name
$email = $_POST["email"]; // Sender's email ID
$message = $_POST["message"]; // Sender's Message
if (empty($_POST["name"])){
$nameError = "Name is required";
$errors = 1;
}
if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
{
$emailError = "Email is not valid";
$errors = 1;
}
if (empty($_POST["message"])){
$messageError = "Message is required";
$errors = 1;
}
}
if($errors == 0){
$successMessage = mail($to, $subject, $body, "From: <$email>");
}
else {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.html\">";
}
if ($successMessage){
print "<meta http-equiv=\"refresh\" content=\"0;URL=thanks.html\">";
}
?>

Add Contact form ajax with shortcode in wordpress

I'm creating a plugin for my contact form using ajax and add shortcode wordpress . I don't get how to do it and it work perfect, and read several forums about the admin- ajax.php but do not understand how to pass data to this file.
This is the code :
<?php
/*
Plugin Name: Formulario de contacto
Plugin URI: http://www.e-world.co
Description: Formulario de contacto con ajax
Version: 1.0
Author: Jorge Moreno
Author URI: http://www.e-world.co
license: GLP2
*/
function the_action_function(){
$adminemail = "jorge.moreno#e-world.co";
if ($_GET['send'] == 'comments')
{
$_uname = $_POST['name'];
$_uemail = $_POST['email'];
$_website = $_POST['website'];
$_comments = stripslashes($_POST['comment']);
$email_check = '';
$return_arr = array();
if($_uname=="" || $_uemail=="" || $_comments=="")
{
$return_arr["frm_check"] = 'error';
$return_arr["msg"] = "Please fill in all required fields!";
}
else if(filter_var($_uemail, FILTER_VALIDATE_EMAIL))
{
$to = $adminemail;
$from = $_uemail;
$subject = "Renew Email: " .$_uname;
$message = 'Name: ' . $_uname . '<br><br> Email: ' . $_uemail . '<br><br> website: ' . $_website . '<br><br> Comment: ' . $_comments;
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n";
$headers .= "From: " . $from . "\r\n";
#mail($to, $subject, $message, $headers);
} else {
$return_arr["frm_check"] = 'error';
$return_arr["msg"] = "Please enter a valid email address!";
}
echo json_encode($return_arr);
}
}
function createAjaxContactForm() {
return '
<div class="form">
<form action="process.php" method="post" name="ContactForm" id="ContactForm" >
<div class="form-group">
<input type="text" class="form-control" name="name" placeholder="Full Name *">
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" placeholder="Email *">
</div>
<div class="form-group">
<input type="text" class="form-control" name="website" placeholder="Website">
</div>
<div class="form-group">
<textarea rows="5" class="form-control" name="comment" placeholder="Your Message *" style="height:175px;"></textarea>
</div>
<div id="message_post"></div>
<input class="btn btn-default" type="submit" value="ENVIAR" name="submitf" id="submitf">
</form>
</div>';
}
add_shortcode('AjaxContactForm', 'createAjaxContactForm');
?>
and my ajax:
jQuery(function(){
jQuery("#ContactForm").submit(function(){
jQuery("#submitf").value='Please wait...';
jQuery.post("password/wp-admin/admin-ajax.php", jQuery("#ContactForm").serialize(),
function(data){
if(data.frm_check == 'error'){
jQuery("#message_post").html("<div class='errorMessage'>ERROR: " + data.msg + "!</div>");
document.ContactForm.submitf.value='Resend >>';
document.ContactForm.submitf.disabled=false;
} else {
jQuery("#message_post").html("<div class='successMessage'>Your message has been sent successfully!</div>");
jQuery("#submitf").value='Send >>';
}
}, "json");
return false;
});
});
This is ajaxurl write this code your-theme/functions.php
<?php function frontend_custom_ajaxurl() { ?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
add_action('wp_head','frontend_custom_ajaxurl');
This is your php function can do anything. And also write this code in your-theme/functions.php file
function your_function() {
parse_str($_POST['data'], $params);
print_r($params)
exit;
}
add_action('wp_ajax_your_function', 'your_function');
add_action('wp_ajax_nopriv_your_function', 'your_function');
This is JQuery.
jQuery("#ContactForm").submit(function(event) {
event.preventDefault();
jQuery("#submitf").value = 'Please wait...';
var data = {
action: 'your_function', // here php function such as your_function
data: jQuery("#ContactForm").serialize(),
};
jQuery.post(ajaxurl, data, function(response) {
......................
});
});
Any confusion comment?
for ajax use this code :
use the below code in .php file and replace $ with jQuery if it not works
$().ready(function() {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
$.post(
ajaxurl, {
'action': 'set_the_city',
//pass all the parameter from the form in key value pairs here
},
function(output) {
console.log(output)
});
});
WordPress provides a hook for ajax call use that instead.
add_action('wp_ajax_set_the_city', 'set_the_city');
add_action('wp_ajax_nopriv_set_the_city', 'set_the_city');
function set_the_city() {
//all the data can be retrieved by $_REQUEST so do the coding for the_action_function() here.
}

Email not sending. Values sent by ajax [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 7 years ago.
I am picking up values and sending hidden field values through an AJAX call and then performing a query to update something in my database. The first initial query finds the id and other $_POST information and works great. However my email is not sending. My alert error message is not showing anything, but is displaying (it is a blank alert).
Does anyone see anything that is wrong with how am I am trying to send to my email or how I'm picking up the valuesin my email my email that it wouldn't send?
hidden input fields..
<input type="hidden" value="<?php echo $approved_id; ?>" id="approved_id" name="id" />
<input type="hidden" value="<?php echo $approved_firstname; ?>" id="approved_firstname" name="firstname" />
<input type="hidden" value="<?php echo $approved_lastname; ?>" id="approved_lastname" name="lastname" />
<input type="hidden" value="<?php echo $approved_username; ?>" id="approved_username" name="username" />
<input type="hidden" value="<?php echo $approved_email; ?>" id="approved_email" name="email" />
ajax call..
$(document).ready(function () {
$('#update_group').on('submit', function (event) {
event.preventDefault();
$.ajax({
url: 'user_group_update.php',
type: 'POST',
data: {
id: $("#approved_id").val(), //id
firstname: $("#approved_firstname").val(), //firstname
lastname: $("#approved_lastname").val(), //lastname
username: $("#approved_username").val(), //username
email: $("#approved_email").val(), //email
// update_group: $("#group_id").val() //group level
update_group: $(this).find( "#group_id option:selected" ).val()
},
success: function (data) {
//do something with the data that got returned
$(".group_success").fadeIn();
$(".group_success").show();
$('.group_success').html('User Permission Level Changed!');
$('.group_success').delay(5000).fadeOut(400);
alert(data);
},
error: function(jqXHR, textStatus,errorThrown )
{
// alert on an http error
alert( textStatus + errorThrown );
}
});
return false;
});
});
user_group_update.php
<?php
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . DIRECTORY_SEPARATOR . 'error.log');
error_reporting(E_ALL);
require_once 'core/init.php';
$approved_id = $_POST['id'];
//test - delete if it doesn't work
$approved_firstname = $_POST['firstname'];
$approved_lastname = $_POST['lastname'];
$approved_username = $_POST['username'];
$approved_email = $_POST['email'];
$change_group = $_POST['update_group'];
$con = mysqli_connect("localhost","","","");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("UPDATE users,user_requests SET users.group=?, user_requests.group=? WHERE users.id=? AND user_requests.user_id=?");
if ( !$stmt || $con->error ) {
// Check Errors for prepare
die('User Group update prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt->bind_param('iiii', $change_group, $change_group, $approved_id, $approved_id)) {
// Check errors for binding parameters
die('User Group update bind_param() failed: ' . htmlspecialchars($stmt->error));
}
if(!$stmt->execute()) {
die('User Group update execute() failed: ' . htmlspecialchars($stmt->error));
}
//test
$email_stmt = $con->prepare("SELECT * FROM users WHERE id=?");
if ( !$email_stmt || $con->error ) {
// Check Errors for prepare
die('User email prepare() failed: ' . htmlspecialchars($con->error));
}
/*if(!$email_stmt->bind_param('ii', $change_group, $approved_id)) {
// Check errors for binding parameters
die('User email bind_param() failed: ' . htmlspecialchars($stmt->error));
}
if(!$email_stmt->execute()) {
die('User email execute() failed: ' . htmlspecialchars($stmt->error));*/
/*
$row = mysqli_fetch_assoc($$email_stmt);
$pending_id = $_POST['id'];
$group_firstname = $row['firstname'];
$group_lastname = $row['lastname'];
$group_username = $row['username'];
$group_email = $row['email'];
$group_email = $row['group'];*/
$to = $approved_email;
$subject = 'There is a new user request to join the Sunday Funday League';
$message = '
<html>
<head>
<title>New SFL User Request</title>
</head>
<body>
<p>Hi '.$approved_firstname.',</p><br>
<p>Your Sunday Funday League Account has been accepted. You have been added to the group. To sign in, click this link
http://sundayfundayleague.com . </p><br>
<p>Thank you,</p>
<p>Administration</p>
</body>
</html>
';
$from = "user-requests#sundayfundayleague.com";
$Bcc = "user-requests-confirm#sundayfundayleague.com";
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
//$headers .= 'To: ' .$to;//. "\r\n";
$headers .= 'From: ' .$from; "\r\n";
$headers .= 'Bcc: '.$Bcc; "\r\n";
// Send the email
mail($to,$subject,$message,$headers);
The mail() function in PHP will return true or false and you'll therefore not be able to see the error in the client.
You can however use error_get_last() when mail() fails as answered here.
Since the mail() function returns true or false you'll be able to create a simple if-statement to check if it was successful:
if(mail($to,$subject,$message,$headers)){
// success
} else {
print_r(error_get_last());
}
Try this to get more information about what's happening in the background.

Email sending with AngularJS and PHP

I have created an application in AngularJS and it has an email contact form and it sends emails using PHP file in server.
Here's my Controller.js part in AngularJS:
$scope.feedbacksubmit= function (){
var name1 = document.getElementById("name").value;
var email1 = document.getElementById("email").value;
var message1 = document.getElementById("message").value;
$http({
url: "http://boost.meximas.com/mobile/email.php",
method: "POST",
data: { name: name1, email: email1, message:message1 }
}).success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
if(status == 200) {
var return_data = data;
if(return_data != 0){
$scope.hide();
//$scope.closeFeedback();
}else{
$scope.showEmailError();
}
}
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log(status);
$scope.showAlertNetwork();
$scope.hide();
});
};
Here's my PHP Code:
<?php
$array = json_decode(file_get_contents('php://input'), true);
$name = $array['name'];
$email = $array['email'];
$message = $array['message'];
if (($name=="")||($email=="")||($message==""))
{
printf("0");
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("mygmail#gmail.com", $subject, $message, $from);
}
?>
The problem arises when I fill in the contact form and hit the Send button. I'm getting $scope.showEmailError();. But I get the email without problem.
And if I try to hit the button without filling the form still getting same $scope.showEmailError(); message.
Why don't you use model values from input? It looks like you try to use AngularJS but you still think with other frameworks in mind
In the following example I'm sending model to php script, if NAME is not filled then PHP returns 404 error and it's handled in AngularJS $http via .error handler. You don't have to add so much extra logic to success to deal with it
http://plnkr.co/edit/sw9RRXb3kdEWXszJdwX3?p=preview
html
<input type="text" ng-model="formData.name" placeholder="name">
<input type="text" ng-model="formData.email" placeholder="email">
<input type="text" ng-model="formData.message" placeholder="message">
javascript
$scope.formData = {
'name': '',
'email': '',
'message': ''
};
$scope.postData = function () {
$http.post('http://edeen.pl/form.php', $scope.formData)
.success(
function(data){
$scope.response = data.replace(/\ /g, ' ').replace(/\n/g, '<br/>') //format response
})
.error(
function(data){
$scope.response = data
})
}
php
$input = json_decode(file_get_contents('php://input'));
if($input->name === ''){
header("HTTP/1.0 404 Not Found");
echo "Something went terribly wrong, missing name maybe?";
return;
}
header('Content-Type: application/json');
var_dump($input);
<?php
$data = json_decode(file_get_contents("php://input"),true);
$name = $data->name;
$email = $data->email;
$sujet = $data->sujet;
$contenu = $data->contenu;
if($name && $email && $sujet && $contenu){
$destinataire = 'bercybilingualschool#gmail.com';
// Pour les champs $expediteur / $copie / $destinataire, séparer par une virgule s'il y a plusieurs adresses
$expediteur = $email;
$copie = 'sss17#gmail.com';
$copie_cachee = 'xxx#xxx.xxx';
$objet = $sujet; // Objet du message
$headers = 'MIME-Version: 1.0' . "\n"; // Version MIME
$headers .= 'Content-type: text/html; charset=ISO-8859-1'."\n"; // l'en-tete Content-type pour le format HTML
$headers .= 'Reply-To: '.$expediteur."\n"; // Mail de reponse
$headers .= 'From: '.$name.'<'.$name.'>'."\n"; // Expediteur
$headers .= 'Delivered-to: '.$destinataire."\n"; // Destinataire
$headers .= 'Cc: '.$copie."\n"; // Copie Cc
$headers .= 'Bcc: '.$copie_cachee."\n\n"; // Copie cachée Bcc
$message = '<div style="width: 100%; text-align: justify; font-weight: bold">hello</div>';
mail($destinataire, $objet, $message, $headers);
}else{
}
?>

Categories

Resources