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.
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") . "
"; //no exception
echo verify(null). "
" //exception
} catch (Exception $e) { //sees exception present and catches it for processing
echo 'Caught exception: ', $e->getMessage(), "
";
}
?>
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]*
)?[ \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]*
)?[ \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.";
}