I am using php mailer for my contact form. I am able to get a success message of the email being sent although I am not receiving the emails.
Here is my code:
contact.php
<form method="post" id="contactForm" action="contactProcess.php">
<div class="clearfix">
<div class="grid_6 alpha fll"><input type="text" name="senderName" id="senderName" placeholder="Name *" class="requiredField" /></div>
<div class="grid_6 omega flr"><input type="text" name="senderEmail" id="senderEmail" placeholder="Email Address *" class="requiredField email" /></div>
</div>
<div><textarea name="message" id="message" placeholder="Message *" class="requiredField" rows="8"></textarea></div>
<input type="submit" id="sendMessage" name="sendMessage" value="Send Email" />
<span> </span>
</form>
contactProcess.php
<?php
include 'library.php'; // include the library file
include "classes/class.phpmailer.php"; // include the class name
if(isset($_POST["sendMessage"])){
$name = $_POST['senderName'];
$email = $_POST['senderEmail'];
$message = $_POST['message'];
$mail = new PHPMailer; // call the class
$mail->IsSMTP();
$mail->Host = SMTP_HOST; //Hostname of the mail server
$mail->Port = SMTP_PORT; //Port of the SMTP like to be 25, 80, 465 or 587
$mail->SMTPAuth = true; //Whether to use SMTP authentication
$mail->Username = SMTP_UNAME; //Username for SMTP authentication any valid email created in your domain
$mail->Password = SMTP_PWORD; //Password for SMTP authentication
$mail->From = $email; //From address of the mail
$mail->FromName = $name;
$mail->Subject = ("Mail From Contact Form"); //Subject of your mail
$mail->IsHTML(true);
$mail->AddAddress("me#add.com");//To address who will receive this email
$mail->AddCC("add#add.com");
$mail->AddReplyTo("add2#add.com", "Me");
$mail->Body = $message;
$mail->AltBody = $message;
$send = $mail->Send(); //Send the mails
if($send){ ?>
<script language="javascript" type="text/javascript">
alert('sent');
window.location = 'contact.php';
</script>
<?php
}
else{ ?>
<script language="javascript" type="text/javascript">
alert('Message failed');
window.location = 'contact.php';
</script>
<?php
}
}
?>
and finally the ajax validation script:
main.js
// Ajax Contact
if ($("#contactForm")[0]) {
$('#contactForm').submit(function () {
$('#contactForm .error').remove();
$('.requiredField').removeClass('fielderror');
$('.requiredField').addClass('fieldtrue');
$('#contactForm span strong').remove();
var hasError = false;
$('#contactForm .requiredField').each(function () {
if (jQuery.trim($(this).val()) === '') {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>*Please fill out all fields.</strong>');
hasError = true;
} else if ($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(jQuery.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>Your email address is incorrect</strong>');
hasError = true;
}
}
});
if (!hasError) {
$('#contactForm').slideDown('normal', function () {
$("#contactForm #sendMessage").addClass('load-color');
$("#contactForm #sendMessage").attr("disabled", "disabled").val('Sending message. Please wait...');
});
var formInput = $(this).serialize();
$.post($(this).attr('action'), formInput, function (data) {
$('#contactForm').slideUp("normal", function () {
$(this).before('<div class="notification-box notification-box-success"><p><i class="icon-ok"></i>Thanks!</strong> Your email was successfully sent. We will get back to you soonest!.</p></div>');
});
});
}
return false;
});
}
I really can't figure out what the problem is.
Related
I have searched for this answer for the past few days and have tried everything to make this work so please help.
I had made a contact form but I will only receive an email if I use the email that the form is submitting to. If I use any other email it will still said the email is sent but when I check my inbox there is nothing there. Same as my junk and sent folders. Although if I complete the form with my email I will get an email in my inbox. (So the form email and the email address submitting to is the same).
This is my index.php
<!DOCTYPE html>
<html>
<head>
<title>Send an Email</title>
</head>
<body>
<center>
<h4 class="sent-notification"></h4>
<form id="myForm">
<h2>Send an Email</h2>
<label>Name</label>
<input id="name" type="text" placeholder="Enter Name">
<br><br>
<label>Email</label>
<input id="email" type="text" placeholder="Enter Email">
<br><br>
<label>Subject</label>
<input id="subject" type="text" placeholder=" Enter Subject">
<br><br>
<p>Message</p>
<textarea id="body" rows="5" placeholder="Type Message"></textarea>
<br><br>
<button type="button" onclick="sendEmail()" value="Send An Email">Submit</button>
</form>
</center>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function sendEmail() {
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
body: body.val()
}, success: function (response) {
$('#myForm')[0].reset();
$('.sent-notification').text("Message Sent Successfully.");
}
});
}
}
This is my sendEmail.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
if(isset($_POST['name']) && isset($_POST['email'])){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$body = $_POST['body'];
require 'vendor/autoload.php';
$mail = new PHPMailer();
//Server settings
$mail->isSMTP(); //Send using SMTP
$mail->Host = 'smtp.mail.yahoo.com'; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = 'atouchof.beauty#yahoo.com'; //SMTP username
$mail->Password = 'aaa'; //SMTP password
$mail->SMTPSecure = 'tsl'; //Enable implicit TLS encryption
$mail->Port = 587; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
$mail->isHTML(true); //Set email format to HTML
$mail->setFrom($email, $name);
$mail->addAddress("atouchof.beauty#yahoo.com");
$mail->Subject = ("$email ($subject)");
$mail->Body = $body;
if($mail->send()){
$status = "success";
$response = "Email is sent!";
}
else
{
$status = "failed";
$response = "Something is wrong: <br>" . $mail->ErrorInfo;
}
exit(json_encode(array("status" => $status, "response" => $response)));
}
?>
This may sound confusing so please ask any questions if you don't understand.
Two problems. Firstly you're forging the from address, which is very probably the cause of your problems. This is well documented, and I recommend following the advice given in the PHPMailer contact form example.
A minor issue is that you're setting this to a non-existent value:
$mail->SMTPSecure = 'tsl';
That should be:
$mail->SMTPSecure = 'tls';
You can call multiple times:
$mail->AddAddress('emailONE#gmail.com', 'Juan');
$mail->AddAddress('emailTWO#gmail.com', 'Pepe');
I recommend use https://mailtrap.io/ for testing emails
I have created a form and I want to mail the form data using PHPMailer. What can I do?
My contact.html file:
<script src="../../Scripts/Custom/contact.js"></script>
<div class="contact-container">
<div class="form-container">
<p class="contactus-heading">Contact us</p>
<div class="inner-form-container">
<div class=" form-row "><input type="text" id="name" class="contact-form-text" placeholder="Your Name here" name="name" /></div>
<div class="form-row"><input type="email" id="email" class="contact-form-text" placeholder="Email" name="email" /></div>
<div class=" form-row"><input type="text" id="phone" class="contact-form-text" placeholder="Phone Number" name="phone" /></div>
<div class="form-row"><textarea class="contact-form-text" id="body" placeholder="your message here" name="message"></textarea></div>
<div class="form-row buttons">
<input type="submit" onclick="sendEmail()" name="btn-send" class="send-btn contact-form-btn" value="send" />
</div>
</div>
</div>
</div>
My Contact.js file:
function sendEmail() {
var name = $('#name')[0].value;
var email = $('#email')[0].value;
var phone = $('#phone')[0].value;
var body = $('#body')[0].value;
if (isNotEmpty(name, email, phone, body)) {
debugger;
$.ajax({
url: '../../Pages/Shared/mail.php',
type: 'POST',
name: name,
email: email,
phone: phone,
body: body,
success: function (response) {
console.log(response);
}, error: function (e) {
console.log(e);
}
});
}
}
function isNotEmpty(name, email, phone, body) {
debugger
if (name != "" && email != "" && phone != "" && body != "") {
return true;
} else {
console.log('some fields are empty');
return false
}
}
My mail.php file:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
if(isset($_POST['name']) && isset($_POST['email'])){
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$body=$_POST['body'];
require_once "../../Libraries/PHPMailer.php"
require_once "../../Libraries/SMTP.php"
require_once "../../Libraries/Exception.php"
$mail = new PHPMailer();
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.gmail.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'mailhere'; // SMTP username
$mail->Password = 'password here'; // SMTP password
$mail->SMTPSecure = 'TLS'; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587;
$mail->isHTML(true);
$mail->setFrom($email, $name);
$mail->addAddress('mailhere'); // Add a recipient
$mail->Subject = 'It is a subject';
$mail->addReplyTo('mailhere');
$mail->Body = $body;
if($mail->send())
$response="Email is sent!";
else
$response= "Something went wrong :<br><br>".$mail->ErrorInfo;
exit(json_encode(array("response" =>$response)));
}
?>
When I filled the information in the form, The error I got is:
The request sent to the Web server used an HTTP verb that is not allowed by the module configured to handle the request. \tA request was sent to the server that contained an invalid HTTP verb. \tThe request is for static content and contains an HTTP verb other than GET or HEAD. \tA request was sent to a virtual directory using the HTTP verb POST and the default document is a static file that does not support HTTP verbs other than GET or HEAD.
I am trying to build an inquiry form and send the data to my email using PHPMailer. I am receiving the data which is submitted through the form but I am not able to send a confirmation to the customer who filled the form. So far this is my form:
<form class="myForm" action="" id="iForm" method="POST">
<input type="text" id="Name" placeholder="Name" required>
<input type="email" id="Email" placeholder="Email" required>
<input type="tel" id="Phone" placeholder="Phone Number" required>
<input type="text" id="Date" placeholder="Schedule a call" required>
<textarea id="Message" rows="5" placeholder="Your Message" required></textarea>
<div class="form-group">
<button type="submit" class="btn cbtn">SUBMIT</button>
</div>
</form>
Passing the data from the submitted form
$("#iForm").on('submit', function(e) {
e.preventDefault();
var data = {
name: $("#Name").val(),
email: $("#Email").val(),
phone: $("#Phone").val(),
date: $("#Date").val(),
message: $("#Message").val()
};
if ( isValidEmail(data['email']) && (data['name'].length > 1) && (data['date'].length > 1) && (data['message'].length > 1) && isValidPhoneNumber(data['phone']) ) {
$.ajax({
type: "POST",
url: "php/appointment.php",
data: data,
success: function() {
$('.success.df').delay(500).fadeIn(1000);
$('.failed.df').fadeOut(500);
}
});
} else {
$('.failed.df').delay(500).fadeIn(1000);
$('.success.df').fadeOut(500);
}
return false;
});
Checking for valid email address
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
Checking for a valid phone number
function isValidPhoneNumber(phoneNumber) {
return phoneNumber.match(/[0-9-()+]{3,20}/);
}
This is the code which I am using from PHPMailer:
$_name = $_REQUEST['name'];
$_email = $_REQUEST['email'];
$_phone = $_REQUEST['phone'];
$_date = $_REQUEST['date'];
$_message = $_REQUEST['message'];
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->Username = "office#myhost.co.uk";
$mail->Password = "********";
$mail->Host = "myhost.co.uk";
$mail->setFrom('office#myhost.co.uk', 'Alex');
$mail->addAddress('me#gmail.com', 'Alex');
$mail->isHTML(true);
$mail->Subject = 'New inquiry from CC';
$mail->Body = <<<EOD
<strong>Name:</strong> $_name <br>
<strong>Email:</strong> $_email <br> <br>
<strong>Phone:</strong> $_phone <br>
<strong>Booking Date:</strong> $_date <br>
<strong>Message:</strong> $_message <br>
I've tried using this, making another instance of PHPMailer and Send the email to the customer with the email they provided.
if($mail->Send()) {
$autoRespond = new PHPMailer();
$autoRespond->setFrom('office#myhost.co.uk', 'Alex');
$autoRespond->AddAddress($_email);
$autoRespond->Subject = "Autorepsonse: We received your submission";
$autoRespond->Body = "We received your submission. We will contact you";
$autoRespond->Send();
}
I've tried a few online "solutions" to this with no success. Any ideas ?
I finally found the solution of my issue. Basically everything above is correct the only thing which I missed was pass the SMTP parameters again to the new instance of PHPMailer. So now the last piece of code which caused the issue looks like that:
if($mail->Send()) {
$autoRespond = new PHPMailer();
$autoRespond->IsSMTP();
$autoRespond->CharSet = 'UTF-8';
$autoRespond->SMTPDebug = 0;
$autoRespond->SMTPAuth = TRUE;
$autoRespond->SMTPSecure = "tls";
$autoRespond->Port = 587;
$autoRespond->Username = "office#myhost.co.uk";
$autoRespond->Password = "********";
$autoRespond->Host = "myhost.co.uk";
$autoRespond->setFrom('office#myhost.co.uk', 'Alex');
$autoRespond->addAddress($_email);
$autoRespond->Subject = "Autorepsonse: We received your submission";
$autoRespond->Body = "We received your submission. We will contact you";
$autoRespond->Send();
}
Thank you for the help everyone.
Attempting to combine a phpmailer with a feature that will allow you to send the form without the need to refresh the page. Generally everything looks good, only the email is not sent. On a clear code about phpmailer everything works.
I would like the e-mail to be sent without the need to refresh the page. Maybe someone had a similar problem?
index.html
<form name="ContactForm" method="post" action="">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name">
</div>
<div class="form-group">
<label for="email">Email Address:</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea name="message" class="form-control" id="message"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<div class="message_box" style="margin:10px 0px;">
</div>
<script>
$(document).ready(function() {
var delay = 2000;
$('.btn-default').click(function(e){
e.preventDefault();
var name = $('#name').val();
if(name == ''){
$('.message_box').html(
'<span style="color:red;">Enter Your Name!</span>'
);
$('#name').focus();
return false;
}
var email = $('#email').val();
if(email == ''){
$('.message_box').html(
'<span style="color:red;">Enter Email Address!</span>'
);
$('#email').focus();
return false;
}
if( $("#email").val()!='' ){
if( !isValidEmailAddress( $("#email").val() ) ){
$('.message_box').html(
'<span style="color:red;">Provided email address is incorrect!</span>'
);
$('#email').focus();
return false;
}
}
var message = $('#message').val();
if(message == ''){
$('.message_box').html(
'<span style="color:red;">Enter Your Message Here!</span>'
);
$('#message').focus();
return false;
}
$.ajax({
type: "POST",
url: "ajax.php",
data: "name="+name+"&email="+email+"&message="+message,
beforeSend: function() {
$('.message_box').html(
'<img src="Loader.gif" width="25" height="25"/>'
);
},
success: function(data)
{
setTimeout(function() {
$('.message_box').html(data);
}, delay);
}
});
});
});
</script>
ajax.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// if(isset($_POST['submit'])){
// $name= $_POST['name'];
// $email= $_POST['email'];
// $tel= $_POST['tel'];
// $message= $_POST['message'];
if ( ($_POST['name']!="") && ($_POST['email']!="")){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.mailtrap.io'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'bf4908e76c4186'; // SMTP username
$mail->Password = 'fe1e3963078670'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
//Recipients
$mail->setFrom($email, $name);
$mail->addAddress('pawel#gmail.com', 'Joe User'); // Add a recipient
$mail->addAddress('pawel#gmail.com'); // Name is optional
$mail->addReplyTo('info#example.com', 'Information');
//Attachments
// $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = $message;
$mail->send();
if($send){
echo "<span style='color:green; font-weight:bold;'>
Thank you for contacting us, we will get back to you shortly.
</span>";
}
else{
echo "<span style='color:red; font-weight:bold;'>
Sorry! Your form submission is failed.
</span>";
}
}
Displays the subtitle to me : "Thank you for contacting us, we will get back to you shortly." but unfortunately not the mailbox empty.
Aside from the try/catch problem, you have other issues.
The combination of SMTPSecure = 'tls' and Port = 465 will not work; either change to ssl mode or change Port = 587. This is well-documented in the troubleshooting guide.
Don't use the submitter's address as the from address; it's forgery and will result in your messages being bounced or spam filtered due to SPF failures. Put your own address in the form address, and put the submitter's in a reply-to - see the contact form example provided with PHPMailer.
I solved the problem myself. Below is a solution.
index.html
<form id="contact" method="post" action="">
<fieldset class="margin-10">
<input placeholder="Name" id="name" type="text" tabindex="1" required>
</fieldset>
<fieldset class="margin-10">
<input placeholder="E-Mail" id="email" type="email" tabindex="2" required>
</fieldset>
<fieldset class="margin-10">
<input placeholder="Phone" id="tel" type="tel" tabindex="3" required>
</fieldset>
<fieldset class="margin-10">
<textarea placeholder="Message..." id="message" name="message" tabindex="5" required></textarea>
</fieldset>
<fieldset class="margin-10">
<button type="submit" class="btn btn-default">Submit</button>
</form>
<div class="message_box" style="margin:10px 0px;">
</div>
<script>
$(document).ready(function() {
var delay = 2000;
$('.btn-default').click(function(e){
e.preventDefault();
var name = $('#name').val();
if(name == ''){
$('.message_box').html(
'<span style="color:red;">Proszę podaj swoje dane.</span>'
);
$('#name').focus();
return false;
}
var email = $('#email').val();
if(email == ''){
$('.message_box').html(
'<span style="color:red;">Proszę wprowadź swoją adres email.</span>'
);
$('#email').focus();
return false;
}
if( $("#email").val()!='' ){
if( !isValidEmailAddress( $("#email").val() ) ){
$('.message_box').html(
'<span style="color:red;">Podany adres e-mail jest nieprawidłowy.</span>'
);
$('#email').focus();
return false;
}
}
var tel = $('#tel').val();
if(tel == ''){
$('.message_box').html(
'<span style="color:red;">Proszę wprowadź swoją numer telefonu.</span>'
);
$('#tel').focus();
return false;
}
var message = $('#message').val();
if(message == ''){
$('.message_box').html(
'<span style="color:red;">Proszę wprowadź swoją wiadomość.</span>'
);
$('#message').focus();
return false;
}
$.ajax
({
type: "POST",
url: "mail.php",
data: "name="+name+"&email="+email+"&message="+message+"&tel="+tel,
beforeSend: function() {
$('.message_box').html(
'<img src="images/loader.gif" width="30" height="30"/>'
);
},
success: function(data)
{
setTimeout(function() {
$('.message_box').html(data);
}, delay);
}
});
});
});
//Email validation Function
function isValidEmailAddress(emailAddress) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
return pattern.test(emailAddress);
};
</script>
mail.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
if ( ($_POST['name']!="") && ($_POST['email']!="")){
$name = $_POST['name'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$message = $_POST['message'];
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->CharSet = "UTF-8";
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.noreply.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'noreply#noreply.com'; // SMTP username
$mail->Password = '123'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
//Recipients
$mail->setFrom($email, $name);
$mail->addAddress('no-reply#noreply.com', 'No-Reply); // Add a recipient
$mail->addReplyTo($email, $name);
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Message sent from the website.';
$mail->Body = "$name<br>$tel<br><br>$message";
$mail->send();
echo 'The message has been successfully sent.';
} catch (Exception $e) {
echo 'The message could not be sent.<br>Mailer Error: ', $mail->ErrorInfo;
}}
else {
echo "The message has not been sent.";
}
One that was easy to spot is that you try{} but never catch{} any errors that may be returned.
This falls under exceptions in the manual here: http://php.net/manual/en/language.exceptions.php
Basic rundown is that for every try{} you need to have at least one catch{} or finally{} block for exceptions! You can also have several catch{} blocks for different exception cases.
So according to the manual in your case you would use something like this:
<?php
function verify($x) {
if (!$x) {
throw new Exception('Verification Failed!');
}
return 1;
}
try {
echo verify("Data") . "\n"; //no exception
echo verify(null). "\n" //exception
} catch (Exception $e) { //sees exception present and catches it for processing
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
I have this simple bootstrap form that i run on my localhost, it accepts name email and message and a custom captcha in a form of a math question; On submit i used jquery ajax to fetch the data to emailme.php that contains the phpmailer code.. My problem is, no email was sent even if there's no error and the network status is 200 and i can also see this:
http://localhost/emailme.php?name=myname&email=myemail#gmail.com&message=test
however it works if i just use the phpmailer stand alone code with fixed values. how can i make it work?
HTML:
<form id="emailme" method="post">
<div class="form-group">
<input type="text" class="form-control" name="name" id="name" placeholder="e.g. John Doe">
<span id="err_name" class="text-danger"></span>
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" id="email" placeholder="e.g. example#domain.com">
<span id="err_email" class="text-danger"></span>
</div>
<div class="form-group">
<textarea name="message" id="message" cols="30" rows="10" class="form-control" placeholder="Your message"></textarea>
<span id="err_message" class="text-danger"></span>
</div>
<div class="form-group">
<label for="human">5 + 2 = ?</label>
<input type="text" id="human" name="human" class="form-control" placeholder="Your Answer">
<span id="err_human" class="text-danger"></span>
</div>
<input type="submit" class="btn btn-primary btn-sm" value="Send">
</form>
JQUERY:
$("#emailme").on('submit',function(e){
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var human = $("#human").val();
var emailRegex = /(.+)#(.+)\.(com|edu|org|etc)$/g;
if(name!==''&&email!==''&&message!==''&&human!==''){
if(email.match(emailRegex)){
if(human==7){
$.ajax({
url:'emailme.php',
typ:'post',
data:{name:name,email:email,message:message},
success:function(response){
console.log(response);
$("#mail-status").html(response);
$("#emailme")[0].reset();
},
error:function(XMLHttpRequest,textStatus,errorThrown){
console.log(textStatus+errorThrown);
}
});
}
else{
$("#mail-status").html("unable to submit form, you're not human");
}
}
else{
$("#err_email").append("Invalid email format");
}
}
else if(name==''){
$("#err_name").append("Name cannot be empty");
}
else if(email==''){
$("#err_email").append("Email cannot be empty");
}
else if(message==''){
$("#err_message").append("Message cannot be empty");
}
else if(human==''){
$("#err_human").append("Please answer the security question");
}
});
PHP:
<?php
date_default_timezone_set('Etc/UTC');
require 'phpmailer/PHPMailerAutoload.php';
// Set the email address submissions will be sent to
$email_address = 'myemail#gmail.com';
// Set the subject line for email messages
$subject = 'Test email from localhost using PHPMailer';
// Check for form submission
if(isset($_POST['name'], $_POST['email'], $_POST['message'])){
//Create a new PHPMailer instance
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "myemail#gmail.com";
$mail->Password = "mypassword";
$mail->setFrom($_POST['email'], $_POST['name']);
$mail->addAddress($email_address, 'myname');
$mail->Subject = $subject;
$mail->Body = 'From:'.$_POST['name'].'(' . $_POST['email'] . ')'.'<p><b>Message</b><br/>' . $_POST['message'] . '</p>';
$mail->AltBody = 'This is a plain-text message body';
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
}
?>