Sending Email via PHP Not Working - php

I have a site running on Windows Azure that contains a simple contact form for people to get in touch. Unfortunately, that form isn't work right now...
I have an index.php file that contains the form:
<div class="form">name="name" placeholder="Name" id="contactname" />
<input type="text" name="email" placeholder="Email" id="contactemail" />
<textarea name="message" placeholder="Message" id="contactmessage"></textarea>
<button>Contact</button>
</div>
I then have a JS file like this:
if ($('#contact').is(":visible")) {
$("#contact button").click(function() {
var name = $("#contactname").val();
var message = $("#contactmessage").val();
var email = $("#contactemail").val();
var emailReg = /^[a-zA-Z0-9._+-]+#[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2,3})?(\.[a-zA-Z]{2,3})?$/;
// client-side validation
if(emailReg.test(email) == false) {
var emailValidation = false;
$('#contactemail').addClass("error");
}
else
$('#contactemail').removeClass("error");
if(name.length < 1) {
var nameValidation = false;
$('#contactname').addClass("error");
}
else
$('#contactname').removeClass("error");
if(message.length < 1) {
var messageValidation = false;
$('#contactmessage').addClass("error");
}
else
$('#contactmessage').removeClass("error");
if ((nameValidation == false) || (emailValidation == false) || (messageValidation == false))
return false;
$.ajax({
type: "post",
dataType: "json",
url: "send-email.php",
data: $("#contact").serialize(),
success: function(data) {
$('.form').html('<p class="success">Thanks for getting in touch - we\'ll get back to you shortly.</p>');
}
});
return false;
});
};
and finally, a php file to send the email called send-email.php:
$destination = 'info#clouddock.co'; // change this to your email.
// ##################################################
// DON'T EDIT BELOW UNLESS YOU KNOW WHAT YOU'RE DOING
// ##################################################
$email = $_POST['email'];
$name = $_POST['name'];
$message = $_POST['message'];
$subject = $name;
$headers = "From: ".$name." <".$email.">\r\n" .
"Reply-To: ".$name." <".$email.">\r\n" .
"X-Mailer: PHP/" . phpversion() . "\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\r\n" .
"Content-Transfer-Encoding: 8bit\r\n\r\n";
mail($destination, $subject, $message, $headers);
}
When I fill in the contact form, the JS validation appears to be working, and when I click send the 'Thanks for getting in touch...' text appears, as if the message has been sent. But I don't receive any email. Can anyone advise as to where the problem might be? Could it be Azures configuration blocking the messages from being sent out?

You are using $("#contact").serialize() to get data to send but you've got no elements with ID contact.
You should use $("#contactname, #contactemail, #contactmessage").serialize() (and fix first input ;) ).
And always validate input data in PHP, not only in JS!

Of course it will display the thanks message, all it needs is a response back from the server. What you need is to test whether the mail actually sent or not, then return that back to your original script to determine what message to show.
if(mail($destination, $subject, $message, $headers)) {
return '<p class="success">Thanks for getting in touch - we\'ll get back to you shortly.</p>';
} else {
return '<p class="fail">The e-mail failed to send.</p>';
}
And then set your AJAX to:
$.ajax({
type: "post",
url: "send-email.php",
data: $("#contact").serialize(),
success: function(data) {
$('.form').html(data);
}
});
You'll probably find that you get the fail message, and that could well be the setup of your server, or it could be you not passing the right thing to the mail() function. You then need to debug your script to find out whether the right information is being passed etc.
With Windows servers they need to be configured to pass all mail from the mail() function to an SMTP server, so if that's not been done on your Azure server then your mail will instantly fail.

Related

Issues sending email using my php form

I am trying to set up a simple "Contact Me" form for my website using VB.NET 2015. But I am not able to receive any emails. Here are my files:
PHP:
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");
//if "email" variable is filled out, send email
$email = htmlspecialchars($_POST["email"], ENT_QUOTES);
$subject = htmlspecialchars($_POST["subject"], ENT_QUOTES);
$comment = htmlspecialchars($_POST["comment"], ENT_QUOTES);
$comment = str_replace("\n.", "\n..", $comment);//message can't have \n.
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "From: " . $email . "\r\n";
if(mail("foo#test.com ", $subject, $comment, $headers)){
//no error
exit;
}
echo "Error sending mail";
?>
TYPESCRIPT:
module OnlinePortfolio {
export class ContactMe {
public static Email() {
$.ajax({
url: "SendMail.php",
type: "POST",
data: {
"subject": $("#subject").text(), "email": $("#email").text(), "message": $("#comment").text()
},
success: function (data, status) {
if (data === "") {
alert("Message sent successfully");
}
else {
alert("There was an issue with sending your message");
}
},
error: function (xhr, status, errorDescription) {
console.error('Something happened while sending the request: ' + status + ' - ' + errorDescription);
}
});
}
}
}
HTML
<html>
<form>
Email: <input id="email" type="text" /><br />
Subject: <input id="subject" type="text" /><br />
Message:<br />
<textarea id="comment" rows="15" cols="40"></textarea><br />
<input type="submit" value="Submit" onclick="OnlinePortfolio.ContactMe.Email()">
</form>
<html>
The email provided above is just for this post. I am fairly new to php but based on some research I did this should be working. I get no errors when I click the submit button. I also opened the debug console and get no errors as well. Can someone please help me understand why I am not receiving emails?
Many thanks in advance!
Please, use PHPMailer(https://github.com/PHPMailer/PHPMailer)) from local
It seems like you are using PHP in-built mail function. Unfortunately, It will not work on localhost.
You need to run that from a remote server to make it work.
In case, if you want to run that from localhost, use a third party library say phpmailer.
1:localhost can`t use mail() for send e-mail , first upload to server . if you must use in localhost use phpmailer (https://github.com/PHPMailer/PHPMailer)
2:your not set action ! in real html script set it

Cannot send email using mail function

First question and first time looking at PHP so please bear with me.
I currently have the below jQuery which is calling a php file:
$(document).on('click', '#btnContactUs', function () {
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("input#message").val();
var dataString = 'name='+ name + '&email=' + email + '&subject=' + subject + '&message=' + message;
$.ajax({
type: "POST",
url: "php/message.php",
data: dataString,
success: function(response) { alert(response); }
});
return false;
});
The console is logging the call as successful (XHR finished loading: POST "php/message.php").
Below is the full script in the file:
<?php
$to = 'nobody#example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
The email is not being sent/received (I am checking Spam also).
The files are hosted on a web server which has PHP installed. The alert box is popping up, but empty. The initial AJAX call is made from a submit button on a webpage.
EDIT: I am sending this to my personal email, which I have not included above.
EDIT: Even when visiting the URL of the script the email is still not being sent.
FINAL EDIT: The resolution is that my server did not have PHP mail installed - it is not supported as it is considered unreliable and therefore they recommend SMTP. To figure this out I used DrewT's solution of using SSH to check for "which sendmail"
Hope this scenario helps someone in the future.
Thanks all.
What seems to be happening is you are not sending your information in the correct format because you don't parse your var dataString on the server. I would try something like:
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("input#message").val();
Then in your post function:
$.ajax({
type: "POST",
url: "php/message.php",
data : { name: name, email: email, subject: subject, message: message },
success: function (response, status, err) {
// do stuff...
// NOTE: don't return false or it won't send
// 'return false' only if the form is incomplete
// and you don't want the email sent out prematurely
}
});
Then to receive these vars in your PHP:
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
Now you can send an email like this:
// Enter your send email address
$to = 'email#example.com';
// Add your headers
$header = "from: $name <$email>";
// only send it if we have all the data we need
if( $subject !== "" || " " && $message !== "" || " " && $name !== "" || " " && $mail_from !== "" || " " ) {
$send_contact = mail($to,$subject,$message,$header);
// check if message was sent
// and provide some formatting (html) to send along in our response
if ($send_contact) {
echo '<div class="msg-sent">
Your message was sent successfully yay!
</div>';
}
else {
echo '<div class="msg-send-failed">
SEND FAILED :0
</div>';
}
}
else {
echo '<div class="msg-had-empty">
YOU HAD EMPTY POST VARIABLES :0
</div>';
}
Beyond that you will need to debug using the networks tab in your browser's inspector./ good luck!

jQuery AJAX contact form with PHP mailer jumping to mail page

I'm making a simple contact form, I have an old school php mailer mail.php and a jQuery front page from where I'm calling it.
As I wanted it to work, it should've stayed on same page, but it actually jumps to mail.php and displays the message
Thank you for contacting me. I'll try to reach you ASAP.
Though it does send the mail, thats still not acceptable as that was not my intention. Can anybody find out what I'm doing wrong here ?
Any help appreciated.
PHP:
<?php
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = trim($_POST['message']);
}
$emailTo = 'myEmail#gmail.com';
$subject = 'Contact Form Submission from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nMessage: $message";
$headers = 'From: Saddi website <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
echo "Thank you for contacting me. I'll try to reach you ASAP.";
return true;
?>
FORM (Lot of bootstrap tags there, so to keep it clean I'm just posting ):
<form class="form" action="mail.php" method="post" id="contact-form">
</form>
And here goes my AJAX:
var data_string = jQuery('#contact-form').serialize();
jQuery.ajax({
type: "POST",
url: "mail.php",
data: {name:name,email:email,message:message},
timeout: 6000,
error: function(request,error) {
if (error == "timeout") {
jQuery('#timedout').fadeIn('slow');
setTimeout(function() {
jQuery('#timedout').fadeOut('slow');
}, 3000);
}
else {
jQuery('#state').fadeIn('slow');
jQuery("#state").html('The following error occured: ' + error + '');
setTimeout(function() {
jQuery('#state').fadeOut('slow');
}, 3000);
}
},
success: function() {
jQuery('span.valid').remove();
jQuery('#thanks').fadeIn('slow');
jQuery('input').val('');
jQuery('textarea').val('');
setTimeout(function() {
jQuery('#thanks').fadeOut('slow');
}, 3000);
}
First i will recommend you to use jQuery Form Plugin, very helpful for this kind of ajax post and validations.
jQuery Form
Second, you can use event.preventDefault(); to avoid the default action of the link but it will really depend on how are you triggering your form to the ajax code
event.preventDefault

Use Ajax to show failure message when PHP filter validate email detects an invalid submit

It's the HTML contact form:
<form class="form" method="post" action="mail.php">
<label for="name">Name:</label>
<input class="name" type="text" name="name" value="" placeholder="Full Name" required>
<label for="email">Email:</label>
<input class="email" type="text" name="email" value="" placeholder="Email" required>
<label for="message">Message:</label>
<textarea class="message" rows="4" cols="20" name="message" placeholder="Type..." required></textarea>
<input type="submit" value="Send">
It's the Ajax I use for my contact form:
$('.form').submit(function() {
var name = $(".name").val();
var email = $(".email").val();
var message = $(".message").val();
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : dataString,
cache : false,
success : function() {
$(".form").hide();
$(".notice").fadeIn(400);
}
});
return false;
});
And it's my mail.php (I found here):
<?php
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "example#example.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
} else {
header("Location: your_form.html");
}
I just want to add an "Invalid Email Address" message to my form with Ajax (in order to show besides the form, Not in another page)
In the current form when the user submit a filled and valid inputs, it shows a Success message (.notice), but nothing happen when you submit the form with an invalid email address.
You can try passing arrays from your PHP script back to your AJAX response as data, and let your script handle whatever that is passed back :) In my example below, I have chosen to pass the PHP response back to your AJAX script using the json_encode function, and arbitrarily selected a type of status code that will be read by your JS function to take appropriate action :)
Also, in order your $.ajax to read JSON data correctly, you should include the line dataType: "json" in the function.
Overall, the suggested changes will be:
Echo a response from your PHP script in JSON format using json_encode()
Allows your PHP script to pass the response to your JS script
Ensure that your AJAX function reads the JSON format, and then take the appropriate action
For example, in your PHP script, you can use:
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
// If email is valid
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "example#example.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
if(mail($recipient, $subject, $formcontent, $mailheader)) {
// If mail is sent
// Status is arbitrary. You can use a string, number... I usually use numbers
$resp = array("status"=>1, "message"=>"Mail successfully sent.");
} else {
// If sending failed
$resp = array("status"=>2, "message"=>"Error with sending mail.");
}
} else {
// If email failed filter check
$resp = array("status"=>3, "message"=>"You have provided an invalid email address. Please check the email address provided.");
}
// Echos the $resp array in JSON format, which will be parsed by your JS function
echo json_encode($resp);
In your JS file, you can parse the JSON response:
$('.form').submit(function() {
// Define variables to construct dataString. You don't need to use var to declare each variable individually ;)
var name = $(".name").val(),
email = $(".email").val(),
message = $(".message").val();
// Construct dataString
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
// Ajax magic
$.ajax({
type: "POST",
url: "mail.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data) {
if(data.status == "1") {
$(".form").hide();
$(".notice").fadeIn(400);
} else if (data.status == "2") {
// Error handling for failure in mail sending
} else if (data.status == "3") {
// Error handling for failure in email matching
} else{
// Catch all other errors
}
}
});
return false;
});
First change your PHP to output Invalid Email Address in case for invalid email address, then check if that message exists as response from ajax:
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "example#example.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
}else{
echo "Invalid Email Address";
}
And change ajax to:
$('.form').submit(function() {
var name = $(".name").val();
var email = $(".email").val();
var message = $(".message").val();
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : dataString,
cache : false,
success : function(data) {
if(data.indexOf("Invalid Email Address") >= 0){
alert("Invalid Email Address");
}else{
$(".form").hide();
$(".notice").fadeIn(400);
}
}
});
return false;
});
You're going to want to use regular expressions for this, and filter_var. We'll be validating in both Javascript and PHP because the user might not have Javascript enabled.
The regular expressions I normally use to validate emails is this:
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
When your forms gets submitted you'll want to run something like this:
var email = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
if(email.test($('.email').val()) === FALSE) {
$('.notice').html('<strong>Invalid email address!</strong>').show();
return false;
}
In your PHP once you've checked if the POST request is valid and has all the fields you need you'll want to run filter_var with the FILTER_VALIDATE_EMAIL parameter. filter_var returns a boolean.
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
echo 'Invalid email address!';
exit;
}

how to send a body from a textarea from a .js page to a .php page

I've been looking all over StackOverflow and other forum sites, but I still don't know how to acomplish what I'm doing.
I want to send personalized emails (can be text or html) in a website I'm developing.
I'm using ajax to send the list of mails, the subject and the body. The code looks like this
This is the .js
function loadsentmail(){
var subject = document.getElementById("subject_title").value;
var content = tinyMCE.get('content').getContent();
var from = "somemail#mail.com";
var body = new Array();
body[0]=content;
$.ajax({
type:'POST',
url:'sendmail.php?mails='+mails+'&names='+names+'&idgroup='+idGrupo+'&subject='+subject+'&body='+body+'&from='+from+'&flag=1',
data: {},
success:function(result){
alert("Mail sent correctly");
},
error:function(){
alert("Mail was not sent");
}
});
}
This is the .php
$to = $_GET['mails'];
$names = $_GET['names'];
$subject=$_GET['subject'];
$from = $_GET['from'];
$body = $_GET['body'];
$flag=$_GET['flag'];
$groupId=$_GET['idgroup'];
echo $flag;
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: Some Company <somemail#somemail.com>\r\n";
$headers .= "Reply-To: somemail#somemail.com\r\n";
$headers .= "Return-path: somemail#somemail.com\r\n";
$headers .= "Cc: somemail#somemail.com\r\n";
$headers .= "Bcc: somemail#somemail.com\r\n";
switch($flag)
{
case 1:
if (mail($to, $subject,$body,$headers)) {
echo("<p>Message successfully sent!</p>");
}
else {
echo("<p>Message delivery failed...</p>");
}
break;
}
So far so good, I tested with small body, and it worked, but once I pasted a big html file, I got the following error
<h1>Request-URI Too Large</h1>
<p>The requested URL's length exceeds the capacity
limit for this server.<br />
</p>
What is the best practice to send a big Body from a .js to a .php?? I've search a lot throughout the internet but I still can find an answer. Please help me :S
$.ajax({
type:'POST',
url:'sendmail.php',
data: {
mails: mails,
names: names,
idgroup: idGrupo,
subject: subject,
body: body,
from: from,
flag:1
},
type: "POST",
success:function(result){
alert("Mail sent correctly");
},
error:function(){
alert("Mail was not sent");
}
});
Post will allow the larger data set and with jquery ajax you should send the data using the data object even if you use GET.
Also I believe (I'm a perl not a php dev so you will need to look this up) you will need to change your php to grab from the Post obj.
$to = $_GET['mails']; will become $to = $_POST['mails']

Categories