How to add form validation to phpmailer? - php

I am a newbie to PHP, and I am currently using phpmailer to let my clients send emails to me, but a bot is apparently taking advantage of it and sends 3 emails at exactly the same time everyday. So I've been trying to add validation to the form using PHP as javascript can be stopped to avoid validation.. Could you guys please help me add validation to this? I just need to validate name and email. Thank you so much in advance.
PS. I removed some parts of the code for privacy.
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$proptypes = $_POST['proptypes'];
$units = $_POST['units'];
$purchaseOrRefi = $_POST['purchase'];
$loans = $_POST['loans'];
$income = $_POST['income'];
$apt = $_POST['apartment'];
$message = $_POST['message'];
$body = "<b>[From]</b><br>$name<br><br> <b>[E-Mail]</b><br>$email<br><br> <b>[Phone #]</b><br>$phone<br><br> <b>[Address]</b><br>$address<br><br> <b>[Type of Property]</b><br>$proptypes<br><br> <b>[# of Units]</b><br>$units<br><br> <b>[Purchase or Refi?]</b><br>$purchaseOrRefi<br><br> <b>[Amnt of Loans Requested]</b><br>$loans<br><br> <b>[Total Income]</b><br>$income<br><br> <b>[Total Apt Expense]</b><br>$apt<br><br> <b>[Message]</b><br>$message<br><br>";
$mail->Subject = 'Someone wants to hear more about your mortgage programs!';
$mail->Body = $body;
$mail->From = '';
$mail->FromName = '';
// Add a recipient
$mail->addAddress('');
$mail->addAddress('');
$mail->addAddress('');
$mail->addAttachment($_FILES['attachment']['tmp_name'], $_FILES['attachment']['name'], 'base64', $_FILES['attachment']['type']); // Add attachments
$mail->isHTML(true);
if(!$mail->send()) {
echo 'Message could not be sent. Please try again.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Your message has been sent! We will get back to you soon!';
}
?>

Related

PHPmailer not sending mail when message field is empty but is not required?

http://nodeiterator.pl/
Why my php mailer script is not sending mail when message field is empty but is not required ? I get the message "please try again later". What am I missing ?
This is my script:
$msg = "";
use PHPMailer\PHPMailer\PHPMailer;
include_once "phpmailer/src/PHPMailer.php";
include_once "phpmailer/src/Exception.php";
if (isset($_POST['submit'])) {
$subject = $_POST['subject'];
$email = $_POST['email'];
$message = $_POST['message'];
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != "") {
$file = "attachment/" . basename($_FILES['attachment']['name']);
move_uploaded_file($_FILES['attachment']['tmp_name'], $file);
} else
$file = "";
$mail = new PHPMailer();
$mail->addAddress('piterdeja#gmail.com');
$mail->setFrom($email);
$mail->Subject = $subject;
$mail->isHTML(true);
$mail->Body = $message;
$mail->addAttachment($file);
if ($mail->send())
$msg = "Your email has been sent, thank you!";
else
$msg = "Please try again!";
}
I don't think PHPMail by default will let you send an email with an empty body, but you can just go:
$mail->AllowEmpty = true;
Check the error returned:
if(!$mail->Send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
Normally phpmailer does not accept an empty body, you must force it using the attribute $mailer->AllowEmpty = true;

Mail send with PHPMailer doesn't work

So I'm trying to use PHPMailer to handle the email form on my website.
I wrote the code here based on a tutorial I found.
<?php
error_reporting(E_ALL);
require_once("class.phpmailer.php");
include("class.smtp.php");
$email = new PHPMailer();
//
// Set server details for send
//
$email->IsSMTP();
$email->Host = "mail.loganyoung.za.net";
$email->Port = 25;
$email-SMTPAuth = true;
$email->Username = "<my email>";
$email->Password = "<my password>";
//
// Send mail from the contact form
//
$to = "<my email>";
$from = $_POST["from"];
$name = $_POST["name"];
$subject = "From web: ".$_POST["subject"];
$message = $_POST["message"];
$body = "<p>Hi Logan,</p>";
$body .= "<p>You have received a new query on your website.<br />Please see below:</p>";
$body .= "<p>";
$body .= str_replace("\r\n", "<br />", $message);
$body .= "</p>";
$email->SetFrom($from, $name);
$email->AddReplyTo($from, $name);
$email->AddAddress($to, "LoganYoung.za.net");
$email->Subject = $subject;
$email->Body = $body;
$email->IsHTML = true;
session_start();
if(!$email->Send()) {
$_SESSION["mailresult"] = "success";
echo "success";
} else {
echo "<p>Failed:</p><p>".$email->ErrorInfo."</p>";
$_SESSION["mailresult"] = "failed";
$_SESSION["mailerror"] = $email->ErrorInfo;
}
?>
I figure possible reasons for it not sending could be...
Incorrect SMTP details (possibly send without SMTP auth to resolve?)
Handler isn't getting POST data (the ajax that sends it seems to work fine though)
Some problem with this code that I'm not able to identify...
As a means of eliminating possibilities, can anyone spot anything wrong with the code here? If so, what's wrong, and how do I fix it?
Thanks in advance!
$email-SMTPAuth = true;
Isn't that supposed to be:
$email->SMTPAuth = true;

PHPMailer wont send to email with Hyphen IE-#blah-blah.com

I have a simple contact form that uses PHPMailer to send it's information to the admin. Everything works fine when the results are sent to an e-mail with out a hypen such as blah#blah.com. As soon as I change the address to an e-mail with a hypen like blah#blah-blah.com, I get this error.
"Could not instantiate mail function. Mailer Error: Could not instantiate mail function."
Is this a bug with PHPMailer?
Here's my code
<?php
require_once('class.phpmailer.php');
$question_for = $_POST['question_for'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$company = $_POST['company'];
$comment = $_POST['comment'];
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = eregi_replace("[\]",'',$body);
$mail->AddReplyTo("donotreply#blah-blah.com","DoNotReply");
$mail->SetFrom('donotreply#blah-blah.com', 'DoNotReply');
switch ($question_for) {
case "Sales":
$address = "Sales#blah-blah.com";
$mail->AddAddress($address, "Blah");
$mail->Subject = "Message from Sales";
break;
case "Service":
$address = "service#blah-blah.com";
$mail->AddAddress($address, "Blah");
$mail->Subject = "Message from Service";
break;
case "Career":
$address = "career#blah-blah.com";
$mail->AddAddress($address, "Blah");
$mail->Subject = "Message from Career";
break;
}
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML("
Question For:".$question_for."<br />
Name:".$name."<br />
Phone:".$phone."<br />
Email:".$email."<br />
Company:".$company."<br />
Comment:".$comment."<br />");
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
header('Location: http://blah.com/contact/?sent');
}
?>
Checking even more, I see that this works
<?php
mail("test#blah.com", "Test Email", "Testing"); ?>
but this does not
<?php
mail("test#blah-blah.com", "Test Email", "Testing"); ?>

PHPMailer doesn`t work with AddAddress property set

I'm trying to create a contact form using phpMailer and I get in firebug this:
NetworkError: 500 Internal Server Error - path/process.php
uncaught exception: [object Object]
each time I'm trying to run the code below.
Please note that the error is not shown anymore if I remove $mail->AddAddress line, that's why I suspect this line to be the cause.
Instead a new error is displayed: You must provide at least one recipient email address when I remove it.
<?php
$name = $_POST['firstName'];
$email = $_POST['email'];
require("phpmailer.inc.php");
$mail = new PHPMailer(true);
$mail->IsMail();
$mail->From = $email;
$mail->Subject = "subject ";
$mail->Body = "From $name with email: $email";
$mail->WordWrap = 50;
$mail->AddAddress('my_address#gmail.com','my name');
$mail->Send();
?>
Thanks!
Rewrite it to:
<?php
$name = $_POST['firstName'];
$email = $_POST['email'];
require 'phpmailer.inc.php';
try {
$mail = new PHPMailer(true);
$mail->IsMail();
$mail->From = $email;
$mail->Subject = "subject ";
$mail->Body = "From $name with email: $email";
$mail->WordWrap = 50;
$mail->AddAddress('my_address#gmail.com','my name');
$mail->Send();
} catch (Exception $e) {
echo $e->getMessage();
}
and you will catch the error

PHP Mailer shows no errors but doesn't send the email

I'm creating a booking form as a favour but have decided to send mail via the domain, not the server. This is mainly for better security and less limits in responses and data transfers.
I've been working on this for the last few days and trying to teach myself how to get it to work. I now have a very simple working example which can be seen here below.
This is the simple booking form:
<form method="post" name="process.php" action="process.php">
<p>Name:</p><br><input type="text" name="name"><br><br>
<p>Email Address:</p><br><input type="email" name="email"><br><br>
<br>
<input type="submit" name="submit" value="Send Email">
Then in process.php I have this working code:
<?php
use PHPMailer\PHPMailer\PHPMailer;
if(isset($_POST['submit']))
{
// Values need to be santiised
$name = $_POST['name']; //Name of the person requesting a booking
$email = $_POST['email']; //Email of the person requesting a booking
require '../vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Host = 'smtp.hostinger.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'test#handler.net';
$mail->Password = '[PASSWORD]';
$mail->setFrom('test#handler.net'); // All emails would be sent from the handler.net domain to the bookings email of the other domain. (Using test to test, will be noreply)
$mail->addAddress('bookings#salon.com'); // Recipient of the email should be the bookings address, this won't change.
$mail->addReplyTo($email); // The reply to address will be the email address of the user who submitted the booking enquiry.
$mail->addBCC('outbox#handler.net'); // This is to keep a record of all emails that have been sent. Responses will also be saved to a CSV file.
$mail->Subject = 'Booking Request'; // Subject of the email sent to bookings#salon.com that the form responses will be contained within.
$mail->isHTML(TRUE);
$mail->Body = 'Booking request from '.$name.' with email '.$email; // Shows the salon the form response via the email and when they reply a new thread should start in order to compose a new email to reply to the email of the form submitter.
if(!$mail->send()) { // Send the email.
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
}
?>
The code above works and sends the emails from the right address, to the right address. That was on a site in public_html/testing and has been moved to a different site in public_html/booking so the relative paths will be the same. The only files within this directory are index.php (the form) and send.php (the process file with confirmation message)
For some reason this new code with all of the form values will not send. I'm honestly not too sure as to why it won't work now so any pointers at all would be massively appreciated.
<?php
use PHPMailer\PHPMailer\PHPMailer;
if(isset($_POST['submit']))
{
// Values need to be santiised
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$service = $_POST['service'];
$date = $_POST['date'];
$time = $_POST['time'];
require '../vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Host = 'smtp.hostinger.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'noreply#handler.net';
$mail->Password = '[PASSWORD]';
$mail->setFrom('Handler | Bookings'); // Emails sent via Noreply.
$mail->addAddress('bookings#salon.com'); // Email form responses sent to bookings#salon.com
$mail->addReplyTo($email); // Reply to the user who submitted the form.
$mail->addBCC('outbox#handler.net'); // Store record of all emails sent via the system.
$mail->Subject = 'Booking Request'; // Subject of the email sent to bookings#salon.com that the form responses will be contained within.
$mail->isHTML(TRUE);
$mail->Body = '
Booking request from '.$forename.' with email '.$email;'
Test Values: $forename $surname $email $phone $service $date $time
if(!$mail->send()) { // Send the email.
echo '';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo '';
}
}
?>
I don't need the echo statements at the end, I just need the email to send following this sort of format:
<img src="https://via.placeholder.com/300x150" width="15%">
<p><b>Name:</b> $forename $surname</p>
<p><b>Email:</b> $email</p>
<p><b>Phone:</b> $phone</p>
<p><b>Service:</b> $service</p>
<p><b>Date:</b> $date</p>
<p><b>Time:</b> $time</p>
I'm just not sure why the emails now will not send when they have done before. Any pointers would be appreciated.
UPDATE
Here's the updated code with the progress made with thanks to Mr Perfect
<?php
mail("bookings#salon.com", "test", "message");
use PHPMailer\PHPMailer\PHPMailer;
if(isset($_POST['submit']))
{
// Values need to be santiised
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$service = $_POST['service'];
$date = $_POST['date'];
$time = $_POST['time'];
$message = <<<DELIMETER
<img src="https://via.placeholder.com/300x150" width="15%">
<p><b>Name:</b> {$forename} {$surname}</p>
<p><b>Email:</b> {$email}</p>
<p><b>Phone:</b> {$phone}</p>
<p><b>Service:</b> {$service}</p>
<p><b>Date:</b> {$date}</p>
<p><b>Time:</b> {$time}</p>
DELIMETER;
require '../vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 3;
$mail->Host = 'smtp.hostinger.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'noreply#handler.com';
$mail->Password = '[PASSWORD]';
$mail->setFrom('Handler | Bookings'); // Emails sent via Noreply.
$mail->addAddress('bookings#salon.com','ADMIN'); // Email form responses sent to bookings#salon.com.
$mail->addReplyTo($email); // Reply to the user who submitted the form.
// $mail->addBCC('outbox#handler.net'); // Store record of all emails sent via the system.
$mail->Subject = 'Booking Request | SUBMISSION'; // Subject of the email sent to bookings#salon.com that the form responses will be contained within.
$mail->isHTML(TRUE);
$mail->Body = $message;
$mail->AltBody = $message;
if(!$mail->send()) { // Send the email.
echo '';
echo '' . $mail->ErrorInfo; // I don't need to echo any errors because the submission page has the text above already.
} else {
echo '';
}
}
?>
You should look at your $mail->addAdress, $mail->addBCC and $mail->addReplyTo fields and follow the correct syntax for those fields.
Test the code below.
<?php
use PHPMailer\PHPMailer\PHPMailer;
if(isset($_POST['submit']))
{
// Values need to be santiised
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$service = $_POST['service'];
$date = $_POST['date'];
$time = $_POST['time'];
require '../vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Host = 'smtp.hostinger.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'test#handler.net';
$mail->Password = '[PASSWORD]';
$mail->setFrom('test#handler.net','Bookings'); // Emails sent via Noreply.
$mail->addAddress('bookings#salon.com',''); // Email form responses sent to bookings#salon.com
$mail->addReplyTo($email,$forename.' '.$surname); // Reply to the user who submitted the form.
$mail->addBCC('outbox#handler.net',''); // Store record of all emails sent via the system.
$mail->Subject = 'Booking Request'; // Subject of the email sent to admin#handler.net that the form responses will be contained within.
$mail->isHTML(TRUE);
$mail->Body = <<<EOD
Booking request from {$forename} with email {$email}.<br />
Contact details: <br />
Full name: {$forename} {$surname}<br />
Email: {$email} <br />
Phone number: {$phone} <br />
Service: {$service} <br />
Date: {$date} {$time}
EOD;
if(!$mail->send()) { // Send the email.
echo '';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo '';
}
}
?>
This block of code is wrong, some quotes are missing
$mail->Body = '
Booking request from '.$forename.' with email '.$email;'
Test Values: $forename $surname $email $phone $service $date $time
To enable variable replacement on a string use double quotes, and you won't need to concatenate variables with dot(.), also this make possible to use escaped caracters like \n, try to adjust your code like this:
$mail->Body = "Booking request from $forename with email $email\n" .
"Test Values: $forename $surname $email $phone $service $date $time";
Firstly we have to view the error so therefore you have to set
$mail->SMTPDebug = 0;
into
$mail->SMTPDebug = 3;
So you can get that error to post against that error.

Categories