This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 7 years ago.
I'm trying to run a php script on a website contact form. It's probably worth mentioning it's from a website template I bought and I have designed the website using this. My html/css/php knowledge is 'absolute beginner level' hence why I am on here...
Below is the php script (this came with the template). However it's not sending email through to the recipient email address. I've been told it's because the script is trying to send email from an external domain (ie the email address of the website visitor) through the domainname.co.uk mail server, and it’s going to reject it - how can I edit this script so that it works?
This is the PHP script:
<?php
session_start();
$email_to = 'enquiries#bonnelhomes.co.uk'; // change with your email
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
if(mail($email_to, $subject, $message, $headers)){
echo "success";
}
else{
echo "failed";
}
This is the html for the contact form:
<form id="contact" class="row" name="form1" method="post" action="send.php" >
<div class="span4">
<label>Name</label>
<input type="text" class="full" name="name" id="name" />
</div>
<div class="span4">
<label>Email <span class="req">*</span></label>
<input type="text" class="full" name="email" id="email" />
<div id="error_email" class="error">Please check your email</div>
</div>
<div class="span8">
<label>Message <span class="req">*</span></label>
<textarea cols="10" rows="10" name="message" id="message" class="full"></textarea>
<div id="error_message" class="error">Please check your message</div>
<div id="mail_success" class="success">Thank you. Your message has been sent.</div>
<div id="mail_failed" class="error">Error, email not sent</div>
<p id="btnsubmit">
<input type="submit" id="send" value="Send" class="btn btn-large" />
</p>
</div>
</form>
Any help would be much appreciated. Many thanks in advance :o)
replace
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
with
$headers = "From: mail#yourdomain.com\r\n";
UPDATE
since it is a contact form don't forget to add your user's details to $message
$message = $name. "<br>" .$email. "<br>" .$message;
security tip, on this line:
$email_to = 'enquiries#bonnelhomes.co.uk';
has security problem. An attacker can modify the headers, message and use your server to send unlimited spam messages to victims.
so add this line for more security:
if (strlen($email_to) > 30 || $email_to !== 'enquiries#bonnelhomes.co.uk') {
exit("Bye Hacker!");
}
If you still have problems sending "from your server" you might let some real email-server do the work. There is some Framework you can use which is called PHP-Mailer.
To use it, you have to download the framework and to place it into your server. Using this, you might wanna use SMTP (login-information from some real email-account).
it would look like:
require './PHPMailer/PHPMailerAutoload.php';
$mailer = new PHPMailer;
here you configure your email account to send the emails from. look on your hosters help-files to find out what you need to use to log in successfully:
$mailer->isSMTP();
$mailer->SMTPAuth = true;
$mailer->Host = 'smtp.strato.de';
$mailer->Username = 'your#sendingaccount.de';
$mailer->Password = 'xxxxxxx';
$mailer->SMTPSecure = 'ssl';
$mailer->Port = 465;
$mailer->From = 'your#sendingaccount.de';
$mailer->FromName = 'Mr Tester';
here you configure your actual email, you want to send:
$mailer->addAddress('enquiries#bonnelhomes.co.uk','Mr Admin');
$mailer->Subject = 'this is a contactform email';
$mailer->AltBody = 'your text with bla and request');
if($mailer->send()){
echo 'yeah man!';
}else{
echo 'some error occured';
}
Normally this is not absolutly necessary but it helps on servers with sendingproblems or if your emails get blockt by spam blockers.
Related
The contact details are not sending. I will appreciate if anyone has any idea what I am doing wrong. The website is already live and I have used the correct email address in PHP. Not sure 100 if there is any info that will go into head of the HTML contact form.
Thanks
HTML Code:
<div class="row">
<div class="col-12">
<br>
<h2 class="contact-title">Get in Touch</h2>
</div>
<div class="col-lg-8">
<form class="form-contact contact_form" action="contact_process.php" method="post" id="contactForm"
novalidate="novalidate">
<div class="row">
<div class="col-12">
<div class="form-group">
<textarea class="form-control w-100" name="message" id="message" cols="30" rows="9"
onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter Message'"
placeholder='Enter Message'></textarea>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input class="form-control" name="name" id="name" type="text" onfocus="this.placeholder = ''"
onblur="this.placeholder = 'Enter your name'" placeholder='Enter your name'>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input class="form-control" name="email" id="email" type="email" onfocus="this.placeholder = ''"
onblur="this.placeholder = 'Enter email address'" placeholder='Enter email address'>
</div>
</div>
<div class="col-12">
<div class="form-group">
<input class="form-control" name="subject" id="subject" type="text" onfocus="this.placeholder = ''"
onblur="this.placeholder = 'Enter Subject'" placeholder='Enter Subject'>
</div>
</div>
</div>
<div class="form-group mt-3">
<a href="#" class="btn_3 button-contactForm" >Send Message</a>
</div>
</form>
</div>
PHP Code:
<?php
$to = "i have used a correct email address";
$from = $_REQUEST['email'];
$name = $_REQUEST['name'];
$subject = $_REQUEST['subject'];
$number = $_REQUEST['number'];
$cmessage = $_REQUEST['message'];
$headers = "From: $from";
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $from . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$subject = "You have a message from your Bitmap Photography.";
$logo = 'img/logo.png';
$link = '#';
$body = "<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8'><title>Express Mail</title>
</head><body>";
$body .= "<table style='width: 100%;'>";
$body .= "<thead style='text-align: center;'><tr><td style='border:none;' colspan='2'>";
$body .= "<a href='{$link}'><img src='{$logo}' alt=''></a><br><br>";
$body .= "</td></tr></thead><tbody><tr>";
$body .= "<td style='border:none;'><strong>Name:</strong> {$name}</td>";
$body .= "<td style='border:none;'><strong>Email:</strong> {$from}</td>";
$body .= "</tr>";
$body .= "<tr><td style='border:none;'><strong>Subject:</strong> {$csubject}</td></tr>";
$body .= "<tr><td></td></tr>";
$body .= "<tr><td colspan='2' style='border:none;'>{$cmessage}</td></tr>";
$body .= "</tbody></table>";
$body .= "</body></html>";
$send = mail($to, $subject, $body, $headers);
?>
The contact details are not sending. I will appreciate if anyone has any idea what I am doing wrong. The website is already live and I have used the correct email address in PHP. Not sure 100 if there is any info that will go into head of the html contact form.
You have to make a couple of changes in your code to make the mail work. First you Have to change the code for the button. It must be like: <button type="submit"class="btn_3 button-contactForm">Send Message</button> you also have to change the code in the PHP file for sending the mail you have to remove the $send and make it just like mail($to, $subject, $body, $headers); You also have to note that not all hosting companies support the mail() PHP function. So make sure your web hosting provider supports the mail() function. If your hosting service does not support the PHP mail() function, you have to use the PHPMailer class. PHPMailer uses SMTP and sends the mail with the form data. You can download the PHPMailer class with composer. There are also other websites you can download that from. After you unzip the downloaded zip file, you would notice there is a folder named PHPMailer which has a lot of other PHP files inside it. You don't have to change any other PHP files. Make sure an autoload.php file is present in the folder, because the autoload.php file is the file which gets and combines all the necessary classes for the SMTP mail. After that, you have to upload the PHPMailer folder to your root directory in your server (with FTP for shared hosting or just copy paste for dedicated servers). First You have to create a gmail or any mail account through which the PHPMailer sends the mail. After creating an account, go to settings of the account and make sure 2 step authentication is disabled. After that also turn on Less Secure app, which you can do from here.
After doing all that, you have to create two PHP files which sends the form data, the first one will be contact_process.php as you mentioned above and the code for the php file will be:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'phpmail/vendor/autoload.php';
if($_POST)
{
require('constant.php');
$user_name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$user_email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$subject = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
$msg = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
$mail = new PHPMailer(true);
// $mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail -> Host = HOST; //this gets called from the constant.php
$mail->Username = USERNAME;
$mail->Password = PASSWORD;
$mail->From = $user_email;
$mail->FromName = $user_name;
$mail->addAddress(RECIPIENT_MAIL,RECIPIENT_MAIL_NAME); //this gets called from the constant.php do not change this
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = "New Response from website :\n\n<br>".
"Name: $user_name\n\n<br>".
"Email: $user_email \n\n<br>".
"Subject: $subject \n\n<br>".
"Message: \n\n <br>". "$msg\n\n<br>";
$mail->AltBody = "This is the plain text version of the email content";
if (!$mail->send()) {
echo json_encode(array('type'=>'error', 'text' => 'Try Again later')); //error sending form
exit;
} else {
//mail sent successfully
header("Location: thankyou.php");//change the link to the thank you page
exit;
}
}
?>
Now a constant.php file must be created where the reciepient and sender must be configured. The code for that will be:
<?php
// SMTP Configuration
define('HOST',"ssl://smtp.gmail.com");
define('USERNAME',"sending-mail#gmail.com"); //mail address of gmail you created
define('PASSWORD',"password-of-sending-mail-acc"); //password of gmail you created
// Recipient Configuration
define('RECIPIENT_MAIL',"recipient#gmail.com"); //enter mail address you want the form data to get received
define('RECIPIENT_MAIL_NAME',"Website"); //name of recipient
?>
Make sure all the files are in the root directory. You can also add the files to other directories but have to change the directory linking for the files.
For more Detailed documentation and source code you can see this.
This question already has answers here:
PHP email form shooting blank emails
(4 answers)
Closed 2 years ago.
I have a contact form on two different websites I have made for clients.
At around 8-9pm everyday a blank message is sent using the contact form and straight to my clients' respective email addresses.
PHP:
<?php
$name = $_POST['full-name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = $_POST['full-name'];
$to = 'mobileguitarworkshop#hotmail.com';
if(!empty($_POST['field'])) die();
$email_from = 'mobileguitarworkshop#hotmail.com';
$email_subject = "Enquiry from $name.\n";
$body = "From: $name.\n".
"Email: $email.\n".
"Message: $message.\n";
$headers = "From: $email \r\n";
$headers .= "Reply-To: $email \r\n";
mail($to, $email_subject, $body, $headers);
header("Location: http://mobileguitarworkshop.co.uk/success.html");
exit();
?>
HTML:
<form action="contact.php" method="post" class="contact-form">
<label for="full-name">Name</label>
<input name="full-name" type="text" id="full-name" required>
<input type="text" id="field" name="field"/>
<label for="phone">Phone</label>
<input name="phone" type="tel" id="phone">
<label for="email">Email address</label>
<input name="email" type="text" id="email" required>
<label for="message">Message</label>
<textarea name="message" id="message"></textarea>
<input name="send" type="submit" value="SEND" id="sendBtn">
</form>
I've tried adding 'required' to the Name and Email Address inputs to stop spammers, and also a hidden field that, if filled, directs them to 'success.html' without posting the message.
If anyone can explain why this is happening that would be great. The hosting service I'm using is 1&1 IONOS.
Thanks,
Jack
The spammers may be sending a request directly to the contact form endpoint, bypassing your form entirely. This means that required fields in the html wont do much to stop that. You'll need to check those properties on the backend to prevent those submissions. Something like this would work:
if(empty($_POST['full-name']) || empty($_POST['email'])) {
die();
}
If I were you, I'd also look into implementing a CSRF token. See How to properly add CSRF token using PHP
While we're talking, we really should sanitize the $_POST['message']; with something like the below to remove any questionable html content your users may have submitted:
$message = strip_tags($_POST['message']);
My PHP form isn't submitting successfully. I keep getting the custom error that I wrote ('Oops there was a problem. Please try again").
any help would be greatly appreciated. I'm totally new to PHP so I'm thinking maybe some of my php variables are linked wrong and arent connecting with my mailer-new.php file?
Thanks in advance,
<section class="form-body">
<form method="post" action="mailer-new.php" class="contact-form" >
<div class="row">
<?php
if ($_GET['success']== 1){
echo " <div class=\"form-messages success\"> Thank you!
your message has been sent. </div>";
}
if ($_GET['success']== -1){
echo " <div class=\"form-messages error\"> Opps there was a
problem. Please try again </div>";
};
?>
<div class="field name-box">
<input type="text" name="name" id="name" placeholder="Who
Are You?" required/>
<label for="name">Name</label>
<span class="ss-icon">check</span>
</div>
<div class="field email-box">
<input type="text" name="email" id="email"
placeholder="name#email.com" required/>
<label for="email">Email</label>
<span class="ss-icon">check</span>
</div>
<div class="field msg-box">
<textarea name="message" id="msg" rows="4"
placeholder="Your message goes here..."/></textarea>
<label for="message">Msg</label>
<span class="ss-icon">check</span>
</div>
<input class="button" type="submit" value="Send"/>
</div>
</form>
</section>
MAILER.PHP
<?php
// Get the form fields, removes html tags and whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"), array(" ", " " ), $name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check the data.
if (empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.conallen.ie/index.php?
success=-1#form");
exit;
}
// Set the recipient email address. Update this to YOUR desired email address.
$recipient = "allenconallen46#gmail.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
mail($recipient, $subject, $email_content, $email_headers);
// Redirect to the index.html page with success code
header("Location: http://www.conallen.ie/index.php?success=1#form");
?>
This code works correctly in my local machine, even though email is not sent response messages are coming correctly. The changes I have done is changed the host name and made the two lined header redirect into one line in the failed response. Also you have mentioned in the HTML the file name as action="mailer-new.php" and the file name mentioned in the question as MAILER.PHP. Are they same in the code?
To check whether the mail is sent or not remove the header redirect and update like this. If you are getting a failed response means mail is not configured in your server.
if(mail($recipient, $subject, $email_content, $email_headers)) {
echo "mail sent";
} else {
echo "mail sent failed";
}
Alternatively you can use the SMTP for sending email. You can use a library called PHP Mailer and can use any of the valid email address like a gmail account. Please have look at this question if that's the case
Sending email with PHP from an SMTP server
This question already has answers here:
How can I send an email using PHP?
(20 answers)
Closed 6 years ago.
I'm a little bit new with with php and i just want to ask how can i make the the "Send Message" button send the inputted information on the form i created to my email.
Here's the code:
<section id="three">
<h2>Email Me!</h2>
<p>You will receive a reply within 24-48 hours.</p>
<div class="row">
<div class="8u 12u$(small)">
<form method="post" action="MAILTO:sample#email.com">
<div class="row uniform 50%">
<div class="6u 12u$(xsmall)"><input type="text" name="name" id="name" placeholder="Name" /></div>
<div class="6u$ 12u$(xsmall)"><input type="email" name="email" id="email" placeholder="Email" /></div>
<div class="12u$"><textarea name="message" id="message" placeholder="Message" rows="4"></textarea></div>
</div>
</form>
<ul class="actions">
<li><input type="submit" value="Send Message" /></li>
</ul>
</div>
<div class="4u$ 12u$(small)">
<ul class="labeled-icons">
<li>
<h3 class="icon fa-home"><span class="label">Address</span></h3>
1234 Somewhere Rd.<br />
Nashville, TN 00000<br />
United States
</li>
<li>
<h3 class="icon fa-mobile"><span class="label">Phone</span></h3>
000-000-0000
</li>
<li>
<h3 class="icon fa-envelope-o"><span class="label">Email</span></h3>
hello#untitled.tld
</li>
</ul>
</div>
</div>
</section>
Thanks!
I'm not quite sure but email from php server almost all of them ends up in spam folder (trust issues by mail provider). But if you're interested, you can send mail via email function:
<?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);
?>
source: PHPDocs
Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.
What I recomend using is Mail sending servive like SendGdrid or MailChimp, those are easy to use and have pretty simpe API to work with. Free plan has a lot to offer, And you can send plain html through their api and it will be fine.
<?php
if(isset($_POST['submit'])) // on submit click no need to action of the form
{
$name = $_POST['name'];
$email = $_POST['email'];
$to = "somebody#example.com";
$subject = "My subject";
$body = "name:" . $name . "Email:" . $email;
$headers = "From: webmaster#example.com" . "\r\n" .
"CC: somebodyelse#example.com";
mail($to,$subject,$body,$headers);
}
?>
I would recommend using PHPMailer to send email from PHP. Here's the steps to accomplish this.
Go to the Github repository.
Download the ZIP.
Extract it in your public_html directory.
include '/path/to/PHPMailer/PHPMailerAutoload.php'; at the top of your PHP script.
Get the values from the HTML form like you normally would.
Here's an example...
index.html
<form action="index.php" method="post">
<input type="email" name="email">
<input type="text" name="name">
<input type="text" name="subject">
<input type="text" name="message">
</form>
index.php
include '/path/to/PHPMailer/PHPMailerAutoload.php';
$email = $_POST['email'];
$name = $_POST['name'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'localhost'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'username'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, "ssl" also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('your email', 'your name'); // from
$mail->addAddress($email, $name); // to
$mail->isHTML(true); // if html
$mail->Subject = $subject;
$mail->Body = $message; //HTML
if($mail->send()){
echo 'Mail sent!';
}
else {
echo 'Mail failed!';
}
Good day,
Newbie here in PHP. I have been working on a website (free template) and got all the functions to work except the Contact Us part of the code. I don't get any errors it just does not send any email to the listed email or send back a response to the sender.
Here is the HTML Side of the code:
<form id="contact-form" action="php/mail.php">
<div class="control-group">
<div class="controls">
<input class="span6" type="text" id="name" name="name" placeholder="* Your name..."/>
<div class="error center" id="err-name">Please enter your name.</div>
</div></div>
<div class="control-group">
<div class="controls">
<input class="span6" type="email" name="email" id="email" placeholder="* Your email..."/>
<div class="error center" id="err-email">Please enter a valid email adress.</div></div></div>
<div class="control-group">
<div class="controls">
<textarea class="span6" name="comment" id="comment" placeholder="* Comments..."></textarea>
<div class="error center" id="err-comment">Please enter your comment.</div>
</div></div>
<div class="control-group">
<div class="controls">
<button id="send-mail" class="message-btn">Send message</button>
</div></div></form>
and this is the mail.php code used:
include 'functions.php';
if (!empty($_POST)) {
$data['success'] = true;
$_POST = multiDimensionalArrayMap('cleanEvilTags', $_POST);
$_POST = multiDimensionalArrayMap('cleanData', $_POST);
//your email adress
$emailTo = "myemail#gmail.com"; //"myemail#gmail.com";
//from email adress
$emailFrom = "myemail#gmail.com"; //"myemail#gmail.com";
//email subject
$emailSubject = "Mail from MyEmail";
$name = $_POST["name"];
$email = $_POST["email"];
$comment = $_POST["comment"];
if ($name == "")
$data['success'] = false;
if (!preg_match("/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email))
$data['success'] = false;
if ($comment == "")
$data['success'] = false;
if ($data['success'] == true) {
$message = "NAME: $name<br>
EMAIL: $email<br>
COMMENT: $comment";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html; charset=utf-8" . "\r\n";
$headers .= "From: <$emailFrom>" . "\r\n";
mail($emailTo, $emailSubject, $message, $headers);
$data['success'] = true;
echo json_encode($data);
}
}
I am really stuck at this point and this is the only issue I have left hope someone can help point out what I am doing wrong.
Regards,
Rafael
in order for a form to send POST requests you need to specify it by adding the method attribute:
<form id="contact-form" action="php/mail.php" method="post">
Is your php mail script placed in the cgi directory? This is my mail script:
<?php $name = trim(strip_tags($_POST['name']));
$email = trim(strip_tags($_POST['email']));
$message = htmlentities($_POST['message']);
$subject = "Some subject";
$to = 'info#xxx.de';
$body = <<<HTML
$message
HTML;
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// send the email
mail($to, $subject, $body, $headers);
// redirect afterwords, if needed
header('Location: ../contact/thx.html');?>
And it is placed in cgi directory.
After much research and help from CodeGoodie I think the blame lies with the Hosting. I had asked how I could check Server logs to detect the error and they just replied I need to upgrade to be able to use that feature (although it is supposed to be part of the feature already). Thanks for all the help guys. I did learn a lot :)