How can I add an expression inside the $mail-> Body in phpMailer? - php

The phone number in a form isn't required. I would like to hide the label if the phone number field didn't collect any data.
Something like this in theory?
$mail->Body = "
<p><strong>Name: </strong> $full_name</p>
<p><strong>Email: </strong> $email</p>".
if ($phone !== ''){
echo '<p><strong>Phone: </strong> $phone</p>';
} else {
echo '';
} . "
<p><strong>Message: </strong> $message</p>
";
But is not the right syntax. How can I do this? p.s. a Ternary expression would even be cleaner, but it didn't work either

Don't echo, append content:
$mail->Body = "<p><strong>Name: </strong> $full_name</p>
<p><strong>Email: </strong> $email</p>";
if ($phone !== ''){
$mail->Body .= '<p><strong>Phone: </strong> $phone</p>';
}
$mail->Body .= '<p><strong>Message: </strong> $message</p>';

Another alternative, which works better in some situations:
if( $phone )
$phone = "<p><strong>Phone: </strong>$phone</p>";
$mail->Body = "<p><strong>Name: </strong>$full_name</p>
<p><strong>Email: </strong>$email</p>
$phone
<p><strong>Message: </strong>$message</p>";

Related

Contact form validation and email send. Works. How to do things better?

This code works and works well although I know there are definitely some redundancies and better ways to do things. For one, instead of using form action=mypage.php, I have all the php with all my html code. When I tried to have it all in mypage.php, none of the variables would be found in $_POST. Though isset would result to true on $_POST. So... weird, and screw it, I put it in with the html. I was trying with WAMP, but wouldn't work on the server either.
Another issue, refresh of the page after submission will send another email as well, which might be resolved if I solve the form action issue above.
How's my validation? Anything recommended to improve the process or security?
<h1><div class="titleWrapper"><div class="titleContact">Contact</div></div></h1>
<div class="contact">
<ul class="contactColumn">
<li>
<div class="fields">
<form method='POST'>
<input type="text" name="name" placeholder="Your Name" maxlength="50">
<input type="text" name="email" placeholder="Your Email" maxlength="80">
<textarea name ="message" placeholder="Your Message" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your Message'" maxlength="2000"></textarea>
<input type="checkbox" name="copy" style="display: inline-block;float:left"><span style="float:left;padding:17px 0 0 5px">Send me a copy</span>
<input type="submit" name="submit" value="Submit">
</form>
</div>
</li>
</ul>
<ul class="contactColumn">
<div class="rightSide">
<p>
Still have questions?
</p>
<p>
Need more information?
</p>
<p>
Feel free to contact us!
</p>
</div>
</ul>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed in your name";
}
}
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["message"])) {
$comment = "";
} else {
$comment = test_input($_POST["message"]);
}
if (empty($nameErr) && empty($emailErr)){
$to = "myemail#email.com";
$subject = "Contact form submission";
$subject2 = "Copy of your contact form";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $name . "\n\n" . $_POST['message'];
$headers = "From:" . $email;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
if (isset($_POST['copy'])) {
mail($email,$subject2,$message2,$headers2); // sends a copy of the message to the sender
}
echo "<div class='errorMessageWrapper'><div class='errorMessage'><div style='color:#333'>
Thank you for contacting us " .
$name .
". We will be in touch shortly. </div></div>";
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
if (!empty($nameErr)) {
echo "<div class='errorMessageWrapper'><div class='errorMessage'><li style='list-style-type: circle;'>" . $nameErr . "</li></div></div>";
}
if (!empty($emailErr)) {
echo "<div class='errorMessageWrapper'><div class='errorMessage'><li style='list-style-type: circle;'>" . $emailErr . "</li></div></div>";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</div>
I was thinking to make the send email simpler with less code i would suggest PHPMailer it is less code and easier to use.
Take a look at the documentation for PHPMailer at: PHPMAILER DOCUMENTATION
PHPMailer should make it easier to read if you understand PHPMailer, and very simple to write.
HERE IS A EXAMPLE:
<?php
require_once "vendor/autoload.php";
$mail = new PHPMailer;
$mail->From = "from#yourdomain.com";
$mail->FromName = "Full Name";
$mail->addAddress("recipient1#example.com", "Recipient Name");
$mail->isHTML(true);
$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";
if(!$mail->send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent successfully";
}
Here is a link for the the sending emails with PHPMailer: Link

PHP mail() script is sending me unwanted emails

I have a simple PHP mailer script and it is sending me an email everyday as if someone has clicked the submit button without any inputs (blank email). Is there a way to suppress this behavior? What should I change in my script? Thanks
$message = $_POST[message];
$name = $_POST[name];
$email = $_POST[email];
$email_message = $name ." has sent you a message: \n" . $message . "\n Please contact " . $name . " with \n Email: " . $email . "\n Phone: " . $phone;
echo "Hi " .$name ."<br> Your Email is: " .$email ."<br><br>And we received the following message: <br>" . $message."<br><a href='../index.html'>Back Home</a>";
mail($to, $subject, $email_message);
?>
Try this code:
$message = $_POST[message];
$name = $_POST[name];
$email = $_POST[email];
$email_message = $name ." has sent you a message: \n" . $message . "\n Please contact " . $name . " with \n Email: " . $email . "\n Phone: " . $phone;
echo "Hi " .$name ." < break tag > Your Email is: " .$email ." < break tag > And we received the following message: < break tag > " . $message." < break tag > <a href='../index.html'>Back Home</a>";
if(isset($_POST[message]) && isset($_POST[name]) && isset($_POST[email]))
{
mail($to, $subject, $email_message);
} else{
echo "Error";
}
Check if the values are empty or not before sending the mail:
// Check if values exist before continuing
if (
isset($_POST['message']) && strlen($_POST['message']) > 0
&&
isset($_POST['name']) && strlen($_POST['name']) > 0
&&
isset($_POST['email']) && strlen($_POST['email']) > 0
)
{
$message = $_POST['message']; // Remember to use single or double quotes!!!!
$name = $_POST['name'];
$email = $_POST['email'];
$email_message = $name ." has sent you a message: \n" . $message . "\n Please contact " . $name . " with \n Email: " . $email . "\n Phone: " . $phone;
echo "Hi " .$name ."<br> Your Email is: " .$email ."<br><br>And we received the following message: <br>" . $message."<br><a href='../index.html'>Back Home</a>";
mail($to, $subject, $email_message);
}
You have to check whether the values that you are about to send are set or not and submit button is clicked.
Sample Form (form.php)
<form method="POST">
<input type="text" name="name" />
<input type="text" name="email" />
<textarea name="message"></textarea>
<input type="submit" name="submit" />
</form>
Callback Page (submit.php)
<?php
if(isset($_POST['submit'])) {
// Your code comes here
// you can use conditions to validate the form
// ex: if(!empty($_POST['message'])) or if(trim($_POST['message']) != "") to avoid empty message submissions
// Regular expressions to validate email addresses / name
}
?>
Alright, so - the problem is that you're not checking wether or not the fields has been filled, so we're doing that and if they haven't filled out all fields, redirect them back to the contact page with something telling why it made an error. Additionally, we're storing the fields temporarily to avoid issues with users have to fill out all fields again, in case they did fill some out.
<?php
session_start(); // For remembering input (please remember to put this before any output)
$message = $_POST[message];
$name = $_POST[name];
$email = $_POST[email];
if( empty($message) || empty($name) || empty($email) )
{
// Redirect back to contact page, but use sessions to remember already filled out fields
$_SESSION['contact_form']['message'] = $message;
$_SESSION['contact_form']['name'] = $name;
$_SESSION['contact_form']['email'] = $email;
header("Location: http://example.com/contact_page");
exit; // Make sure the rest of the script isn't completed
}
if(isset($_SESSION['contact_form'])) // Check if cleaning up is needed
{
unset($_SESSION['contact_form']); //No need to store this after we send the mail
}
$email_message = $name ." has sent you a message: \n\n";
$email_message .= "Please contact " . $name . " with \n Email: " . $email . "\n";
$email_message .= "Phone: " . $phone;
mail($to, $subject, $email_message, "From: youremail#example.com\r\n"); // added a sender header, just for best practices
?>
Hi <?php echo $name; ?><br>
Your Email is: <?php echo $email; ?><br><br>
And we received the following message: <br>
<?php echo $message; ?><br>
<a href='../index.html'>Back Home</a>
Now, that being done, we need to consider the contact page again, because now we need to tell them that an error occurred and fill out the contact fields again, for those fields thet did fill.
<?php
session_start(); // For fetching remembered output input (please remember to put this before any output)
$error = ;
$message = $name = $email = "";
if(isset($_SESSION['contact_form']))
{
$error = true;
$message = $_SESSION['contact_form']['message'];
$name = $_SESSION['contact_form']['name'];
$email = $_SESSION['contact_form']['email'];
unset($_SESSION['contact_form']); // In case they just leave
}
?>
<?php if($error): ?>
<p class="error">You missed some fields, could you please fill them out?</p>
<?php endif; ?>
<form method="post" action="">
<input type="text" name="name" value="<?php echo $name; ?>">
<input type="text" name="email" value="<?php echo $email; ?>">
<textarea name="message"><?php echo $message; ?></textarea>
<input type="submit" name="submit">
</form>
I hope this can give you an idea of some workflow and combining with a little user experience.
$message = $_POST['message'];
$name = $_POST['name'];
$email = $_POST['email'];
$email_message = $name ." has sent you a message: \n" . $message . "\n Please contact " . $name . " with \n Email: " . $email . "\n Phone: " . $phone;
echo "Hi " .$name ."<br> Your Email is: " .$email ."<br><br>And we received the following message: <br>" . $message."<br><a href='../index.html'>Back Home</a>";
if(!empty($message) && !empty($name) && !empty($email)) {
mail($to, $subject, $email_message);
}
I did not include $email_message because it won't be empty from the start since you're assembling it above.
$subject = 'Subject line for emails';
$headers = 'From: Email Tital ' . "\r\n".'X-Mailer: PHP/' . phpversion();
$message = "Your Message"\n\r";
$sentMail = #mail($to_Email, $subject, $message, $headers);
if(!$sentMail) {
echo "Server error, could not send email. Sorry for the inconvenience." ;
} else {
echo "Thank you for enquiry. We will contact you shortly !";
}
You need to check first message field is empty or not,its client site check if you press submit without message it never submit your form,
function empty() {
var x;
x = document.getElementById("message").value;
if (x == "") {
alert("Enter a message first");
return false;
};
}
and
<input type="submit" value="submit" onClick="return empty()" />

Add extra INPUT to contact form email PHP

I'm using some php i found for sending a contact form from my site.
The HTML looks like this:
<div id="wrap">
<div id='form_wrap'>
<form id="contact-form" action="javascript:alert('success!');">
<p id="formstatus"></p>
<input type="text" name="name" value="" id="name" placeholder="Voornaam" required/>
<input type="text" name="email" value="" id="email" placeholder="E-mail adres" required/>
<textarea name="message" value="Your Message" id="message" placeholder="Uw vraag of projectomschrijving" required></textarea>
<input type="submit" name ="submit" value="Offerte aanvragen" />
</form>
</div>
</div>
The PHP looks like this:
<?php
define("WEBMASTER_EMAIL", 'your#emailadress.com');
error_reporting (E_ALL ^ E_NOTICE);
function ValidateEmail($email)
{
$regex = '/([a-z0-9_.-]+)'. # name
'#'. # at
'([a-z0-9.-]+){2,255}'. # domain & possibly subdomains
'.'. # period
'([a-z]+){2,10}/i'; # domain extension
if($email == '')
return false;
else
$eregi = preg_replace($regex, '', $email);
return empty($eregi) ? true : false;
}
$post = (!empty($_POST)) ? true : false;
if($post)
{
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
$error = '';
// Check name
if(!$name || $name == "Name*")
$error .= 'Please enter your name.<br />';
// Check email
if(!$email || $email == "Email*")
$error .= 'Please enter an e-mail address.<br />';
if($email && !ValidateEmail($email))
$error .= 'Please enter a valid e-mail address.<br />';
// Check message
if(!$message)
$error .= "Please enter your message. <br />";
if(!$error)
{
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
echo 'OK';
}
else
echo '<div class="formstatuserror">'.$error.'</div>';
}?>
It works great! BUT i need to add a few more INPUTS in my form. I know how to add those to the html. For instance I added this one:
<input type="text" name="lastname" value="" id="lastname" placeholder="Achternaam" required/>
But I just can't find the good way to add this input to the email that I receive in my mailbox... Where do I add this in the PHP? I tried lots of things...
Hope you guys can help me out!
David
After these lines:
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
You instanciate a variable containing the value for your field (lastname):
$lastname = stripslashes($_POST['lastname']);
Then you validate your input if it's empty or something else:
// Check message
if(!$lastname )
$error .= "Please enter your lastname. <br />";
And finally, you use your variable lastname to display it on the email message:
"From: ".$name." ".$lasname." <".$email.">\r\n"
Et voilà !
EDIT: If you want to use this input on the message, you have the $message variable, and you can do so :
if(!$error)
{
$message .= "<p>Message sent by $lastname";
...
If you didn't want it going in the email headers as an addition to the 'From' or 'Subject', you could also keep appending information to the body of the email, or your $message. For example:
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$subject = stripslashes($_POST['subject']);
$message = "Last Name: " . stripslashes($_POST['lastname']) . "\r\n";
$message .= "Message: " . stripslashes($_POST['message']);
The other options work as well, it really just depends 'where' in the email you want this extra information going.

Receiving Spam from my Form Using PHPMailer

I am coming to stackoverflow for this because everything I search pretty much talks about email from a form using PHPMailer going to a users spam box. But, I need info on receiving spam from the form itself. I use it on a small, very light traffic real estate agents website. She gets spam from time to time and I don't know how to resolve it. PHPMailer seems to be the go to tool for sending email with PHP, so I figure spam/security is pretty well covered. I must be doing something wrong.... I am using class.phpmailer.php of course, and here is my code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$phone = trim($_POST["phone"]);
$message = trim($_POST["message"]);
if ($name == "" OR $email == "" OR $phone == "" OR $message == "") {
echo "You must specify a value for name, email address, phone, and message.";
exit;
}
foreach( $_POST as $value ){
if( stripos($value,'Content-Type:') !== FALSE ){
echo "There was a problem with the information you entered.";
exit;
}
}
if ($_POST["address"] != "") {
echo "Your form submission has an error.";
exit;
}
require_once("phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
if (!$mail->ValidateAddress($email)){
echo "You must specify a valid email address.";
exit;
}
$email_body = "";
$email_body = $email_body . "Name: " . $name . "<br>";
$email_body = $email_body . "Email: " . $email . "<br>";
$email_body = $email_body . "Phone: " . $phone . "<br>";
$email_body = $email_body . "Message: " . $message;
$mail->SetFrom($email, $name);
$address = "email#domain.com";
$mail->AddAddress($address, "A Name Here");
$mail->Subject = "Message from " . $name . " on website contact form";
$mail->MsgHTML($email_body);
if(!$mail->Send()) {
echo "There was a problem sending the email: " . $mail->ErrorInfo;
exit;
}
header("Location: index.php?status=thanks");
exit;
}
The HTML is very simple:
<form id="form" name="form" method="post" action="contact-process.php">
<?php if (isset($_GET["status"]) AND $_GET["status"] == "thanks") { ?>
<p class="form-thanks">Thank you for contacting us. We'll be in touch with you very soon.</p>
<?php } ?>
<label>Name
<span class="small">First and Last</span>
</label>
<input type="text" name="name" id="name" />
<label>E-Mail
<span class="small">name#email.com</span>
</label>
<input type="text" name="email" id="email" />
<label>Phone Number
<span class="small">With area code</span>
</label>
<input type="text" name="phone" id="phone" />
<label>Message
<span class="small">How can we help you?</span>
</label>
<textarea cols="40" rows="8" name="message"></textarea>
<button type="submit">Submit</button>
<div class="spacer"></div>
</form>
A simple technique to avoid spam is to use something called a honey-pot, which is a text field which is not visible to normal users but a dumb spam-robot will probably enter something into that field.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// robot detection
$honeypot = trim($_POST["email"]);
if(!empty($honeypot)) {
echo "BAD ROBOT!";
exit;
}
$name = trim($_POST["name"]);
$email = trim($_POST["real_email"]);
$phone = trim($_POST["phone"]);
$message = trim($_POST["message"]);
// rest stays as is
In your HTML file you need to insert another "hidden" text field which is the honeypot:
<label>E-Mail
<span class="small">name#email.com</span>
</label>
<input type="text" name="email" style="display: none;">
<input type="text" name="email_real" id="email" />
Note how I changed the name of the actual, visible email text field to "email_real". It would be even better to avoid the word "email" completely in the real email field, since many robots are dumb.
The invisible honeypot input field should be called "email" though. Why? Because most robots are scanning for some standard input fields like "email", "address" etc. - so it's important to give the honeypot a common form field name.
Another neat trick is to swap some common field names, i.e swap the name for email and zip fields, so robots will fill in a numeric value for the email address and an email address for the zip code which will fail the validation.
It's not a 100% guarantee to kill all spam but it worked quite well for me without forcing the user to solve an annoying captcha...

PHP mailer not validating after sending a second email

This is an updated msg's with a working code for sending two different emails using php mailer. It also has working validation server site.
You need to create you own mail class or use the normal one.
Hope someone else can use it two!
Thank you!!
<?php
require"validation.php";
ob_start();
$name = trim($_POST['name']);
$email = $_POST['email'];
$comments = $_POST['comments'];
$info_email= 'example#example.com';
$info_name = 'Example';
require"PHPMailer/mail.inc.php";
$cams="$name has just made a comment or posted a question";
$camb= "<html>
<head>
<h3> $name has asked the following question or comment on you website:</h3>
</head>
<body>
$comments <br><br><br>
Their information: <br><br>
<table cellspacing=\"4\" cellpadding=\"4\" border=\"1\">
<tr>
<td align=\"center\">Name:</td>
<td align=\"center\"> $name</td>
</tr>
<tr>
<td align=\"center\">Email:</td>
<td align=\"center\"> $email</td>
</tr>
</table>
<br>
<img src=\"cid:mailhead\" alt=\"shop logo used in emails\" />
Pleasy try to reply as soon as possible.<br>
Thank you!!
</body>
</html>";
$mail = new MailCon;
$mail->IsSMTP();
$mail->isHTML(true);
$mail->From = $email;
$mail->FromName = $name;
$mail->AddAddress($info_email, $info_name);
$mail->Subject = $cams;
$mail->MsgHTML($camb);
if ($mail->Send()) {
$mail->ClearAllRecipients();
$mail->ClearReplyTos();
$mail->ClearCustomHeaders();
$cums = 'Thank you for using our contact form.';
$message = file_get_contents('mail/example.html');
$message = str_replace('%username%', $name, $message);
$message = str_replace('%email%', $email, $message);
$message = str_replace('%comments%', $comments, $message);
$alt_body="Thank you for asking us a question or making a comment. We will reply as soon as possible.";
$mail = new MailCon;
$mail->IsSMTP();
$mail->IsHTML(true);
$mail->From = $info_email;
$mail->FromName = $info_name;
$mail->AddAddress($email, $name); // Add a recipient
$mail->Subject = $cums;
$mail->MsgHTML($message);
$mail->AltBody = $alt_body;
$mail->Send();
}
ob_end_flush();
?>
This is the validation bit wich you can include using require once.
<?php
$name = trim($_POST['name']);
$email = $_POST['email'];
$comments = $_POST['comments'];
if (strlen($name) < 2) {
$error['name'] = "Please enter your name";
}
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address";
}
if (strlen($comments) < 3) {
$error['comments'] = "Please leave a comment.";
}
if (!$error) {
echo "<div class='alert-box success'>Thanks " . $name . ". Your message has been sent.<a href='' class='close' onclick='clearForms()'>×</a></div>";
} # end if no error
else {
$response = (isset($error['name'])) ? "<div class='alert-box alert'>" . $error['name'] . "</div> \n" : null;
$response .= (isset($error['email'])) ? "<div class='alert-box alert'>" . $error['email'] . "</div> \n" : null;
$response .= (isset($error['comments'])) ? "<div class='alert-box alert'>" . $error['comments'] . "</div>" : null;
echo $response;
exit();
} # end if there was an error sending
?>

Categories