"Contact Me" Mail Form in PHP [duplicate] - php

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 1 year ago.
I have setup a "contact me" form on my website and it doesn't work. Here is the code :
Form Markup :
<form class="contactform" method="post" action="php/process-form.php">
<div class="row">
<!-- Name Field Starts -->
<div class="form-group col-xl-6"> <i class="fa fa-user prefix"></i>
<input id="name" name="name" type="text" class="form-control" placeholder="YOUR NAME" required>
</div>
<!-- Name Field Ends -->
<!-- Email Field Starts -->
<div class="form-group col-xl-6"> <i class="fa fa-envelope prefix"></i>
<input id="email" type="email" name="email" class="form-control" placeholder="YOUR EMAIL" required>
</div>
<!-- Email Field Ends -->
<!-- Comment Textarea Starts -->
<div class="form-group col-xl-12"> <i class="fa fa-comments prefix"></i>
<textarea id="comment" name="comment" class="form-control" placeholder="YOUR MESSAGE" required></textarea>
</div>
<!-- Comment Textarea Ends -->
</div>
<!-- Submit Form Button Starts -->
<div class="submit-form">
<button class="btn button-animated" type="submit" name="send"><span><i class="fa fa-send"></i> Send Message</span></button>
</div>
<!-- Submit Form Button Ends -->
<div class="form-message"> <span class="output_message text-center font-weight-600 uppercase"></span>
</div>
</form>
process-form.php :
<?php
if (isset($_REQUEST['name'],$_REQUEST['email'])) {
$name = $_REQUEST['name'];
$mail = $_REQUEST['email'];
$message = $_REQUEST['comment'];
$to = 'redacted#for.privacy';
$subject = 'Contact From My Website';
$headers = "From: ".$name." <".$mail."> \r\n";
$send_email = mail($to,$subject,$message,$headers);
echo ($send_email) ? 'success' : 'error';
}
?>
AJAX :
$(".contactform").on("submit", function() {
$(".output_message").text("Loading...");
var form = $(this);
$.ajax({
url: form.attr("action"),
method: form.attr("method"),
data: form.serialize(),
success: function(result) {
if (result == "success") {
$(".form-inputs").css("display", "none");
$(".box p").css("display", "none");
$(".contactform").find(".output_message").addClass("success");
$(".output_message").text("Message Sent!");
} else {
$(".tabs-container").css("height", "440px");
$(".contactform").find(".output_message").addClass("error");
$(".output_message").text("Error Sending!");
}
}
});
return false;
});
Error message from the ajax shows and I don't receive any mail. This code should be correct but I read that I needed an smtp configuration ? I can setup such a thing in my google business email but I don't know how and how to implement it on the website.

PHP's mail() function does need some configuration in php.ini file in some cases, like using Windows operating system. It is documented in php.net mail documentation page. Either configure the file, if your load will not be hundreds of mails, or use some of the public available libraries for SMTP connection. They provide much more flexibility and usually provide simple api.
On windows
You need to have set up the php.ini
[mail]
SMTP = "your-mail-server-address"
smtp_port = 25
This answer should provide you more than enough explanation and info.
on Ubuntu / Debian
You have to have configured your sendmail client so it can send emails in your network and specified as sendmail command in sendmail_path directive of php.ini file

While you are using mail() function, You should configure STMP in php.ini file.
But you can use PHPMailer especially when dealing with Google email service, Because Google doesn't allow less secure apps by default.
Look for this example below using PHPMailer:
$mail = new PHPMailer;
$mail->From = 'from#example.com';
$mail->FromName = 'Mailer';
$mail->addAddress($_REQUEST['email'], $_REQUEST['name']);
$mail->addCC('cc#example.com');
$mail->Subject = 'Contact From My Website';
$mail->Body = $_REQUEST['comment'];
echo $mail->send() ? "success" : "error";

Related

php mail attachments with message

I have seen this is a common question but through searching I haven't found the answer I need. I have used PHP code to create a mailer with attachments that are located on my server.
My site has a CRUD system and the read.php file displays various elements of an uploaded file. I also have a form on this page which allows the user to enter and email address and message to send on the said file.
My form code is:-
<form class="form-horizontal" action="mailer.php" method="post">
<div class="form-group">
<label class="col-sm-2">Email Address</label>
<div class="col-sm-4">
<input name="doc_email" type="text" placeholder="Enter Email Address to" class="form-control" >
</div>
</div>
<div class="form-group">
<label class="col-sm-2">Message</label>
<div class="col-sm-4">
<input name="doc_message" type="text" placeholder="Enter a message (not mandatory)" class="form-control" >
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Send Email</button>
</div>
</form>
And my mailer.php code is currently;-
<?php
if (isset($_POST['submit']))
{
$file_name = $_POST['file_name'];
$doc_email = $_POST['doc_email'];
$doc_message = $_POST['doc_message'];
require_once('class.phpmailer.php');
$email = new PHPMailer();
$email->From = 'you#example.com';
$email->FromName = 'Your Name';
$email->Subject = 'Message Subject';
$email->Body = $doc_message;
$email->AddAddress = $doc_email;
$path_file_to_attach = '/documents/uploads/';
$file_to_attach = $file_name;
$email->AddAttachment( $path_file_to_attach , $file_to_attach );
return $email->Send();
//redirect user after success
header("Location: index.php");
}
?>
The class.phpmailer.php file is within the same directory (/documents) as the read.php/mailer.php, all I get is a blank screen with no email or errors.
The folder with the files is located in a sub folder called 'uploads'... documents/uploads/
Any help as always is greatly appreciated.
You have two things empty:
if (isset($_POST['submit'])) //this is false, your button must have a name="submit" attribute
$file_name = $_POST['file_name']; // you don't have any element with this name.
Just add to your html:
<input type="text" name="file_name">
And your button
<button type="submit" name="submit"></button>

Issues with HTML PHP Mailer

i I've been trying to get a .php that works with this HTML code for my website (template), I tried using my old .php from my old website and changing the details but that sadly lead to no avail.
I am clueless when it comes to .php and would really appreciate your help!
What would my .php have to contain?
<form action="#" id="contact-form">
<div id="success"></div>
<ul>
<li class="input-name">
<input type="text" id="name" class="required" placeholder="Name">
</li> <!-- END input-name -->
<li class="input-email">
<input type="text" id="email" class="email" placeholder="Email Address">
</li> <!-- END input-name -->
<li class="input-subject">
<input type="text" id="subject" placeholder="Subject">
</li> <!-- END input-name -->
<li class="input-subject">
<textarea rows="7" cols="50" id="message" class="required" placeholder="Message"></textarea>
</li> <!-- END input-name -->
</ul> <!-- END #contact -->
<button type="submit" class="btn btn-primary btn-lg pull-right">Send Message</button>
</form>
if you are not using ajax then write php file name in form action attribute currently there is #. then you php file will be called.
Change the below code
<form action="#" id="contact-form">
to
<form action="mailer.php" method="post" id="contact-form">
hope this will help.
You have to include the in action="#" the php file. example: action="contactForm.php". That's how the HTML code knows where to send the parameters.
Also, make sure your server supports the 'mail' function.
AND!
I have a good standard example for you of a well written mailing php file that I used. So you can check yourself for syntax issues.
<?php
require_once "Mail.php";
if(isset($_POST['email'])) {
$email = $_POST['email']; //this is how you get your variables from the HTML file. 'edit' is the id of the element.
$email_to = "yourEmail#example.com";
$host = "ssl://smtp.gmail.com:465"; //use your email host - this example is gmail based. (you can search for your own email host via google).
$username = 'username#example.pro';
$password = 'yourPass';
$email_subject = "You have a new email from $email via example.com website";
$message = $_POST['text'];
$headers = array ('From' => $email, 'To' => $email_to,'Subject' => $email_subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($email_to, $headers, $message);
if (PEAR::isError($mail)) {
echo($mail->getMessage());
} else {
echo("Message successfully sent!\n");
}
}
In case of sending emails with ajax - it's an other thing.. and I can help you with that too.

Unable to receive mails using codeigniter email class and yahoo mail as the sender

Im trying to create a "contact us" form where visitors will be able to email the site owner.
so far, my form works if the visitor who filled up the form uses a gmail address. but once they use a yahoo email address the recipient(site owner) does not receive the mail
below is how i did the form
controller
public function send_email(){
$data = $_POST;
$new = $this->base_model->send_email($data);
$this->session->set_flashdata("email_status","Message successfully sent");
redirect(base_url("contact"));
}
model
public function send_email($email_data)
{
$from = $email_data['email'];
$subject = $email_data['subject'];
$message = $this->load->view("emails/message",$email_data,TRUE);
$config['crlf'] = "\n";
$config['mailtype'] = "html";
$config['protocol'] = "sendmail";
$this->load->library('email');
$this->email->initialize($config);
$this->email->from($from,$email_data['name']);
$this->email->to("site owner email address goes here");
$this->email->subject($subject);
$this->email->message($message);
$this->email->send();
return $this->email->print_debugger();
}
view
<?php
$attributes = array("id"=>"form_req");
echo form_open("send_email",$attributes);
?>
<div class="controls">
<label>Name</label>
<input type="text" name="name" class="span12 req">
</div>
<div class="controls">
<label>Email</label>
<input type="text" name="email" class="span12 req">
</div>
<div class="controls">
<label>Subject</label>
<input type="text" name="subject" class="span12 req">
</div>
<div class="controls">
<label>Message</label>
<textarea name="message" class="span12 req"></textarea>
</div>
<button class="btn"><i class="fa fa-send"></i> Send</button>
<?php
echo form_close();
?>
have i missed something? or is there a workaround for this?
Is there any reason that the email needs to come "from" the email address that filled in the form? I've had issues in the past with spam filters, Yahoo being one of them, spamming emails where the domain of the website sending the email doesn't match the email address the email is "from". And with good reason, I suppose. Yahoo may be discarding this dangerous looking "spam" before it even reaches the ordinary spam box.
I would try having the emails always come from noreply#your-domain-here.com and add a reply to header if you absolutely want the owner to be able to reply directly to the email.
EDIT:
Found this old question with a similar issue, which suggests that changing the from email should solve it: Everytime my mail goes to spam in phpmailer

Form fires every time Website is Accessed [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
My website has a form that fires every time the website is accessed. It's still in testing phases so I get over 100 BLANK emails a day just from refreshing the page (and yes, all of the inputs are required). The tricky part is that I have a jquery script included. The script fires when you hit the submit button: it then refreshes the page and scrolls down (using a hashtag) to below my form with a message that basically says "thanks for emailing me!"
My code is posted below, but what I need to know is why I keep getting these blank emails even when the input fields are required! I am still very very new to php and jquery.
<?php
$to = 'design#carolbarone.com' ;
$subject = $_POST['subject'] ;
$name = $_POST['name'] ;
$email = $_POST['email'] ;
$text = $_POST['message'] ;
$message = "From: $name \nEmail: $email \nMessage: $text \n";
$sent = mail($to, $subject, $message) ;
if($sent) {
echo "";
}else{
echo "";
}
?>
<form data-abide name="input" action="index.php#hashtag" method="Post" id="theForm">
<div class="row">
<div class="small-10">
<div class="row">
<div class="small-12 columns name-field">
<input type="text" name="name" required id="right-label" placeholder="Name">
<small class="error">Name is required.</small> </div>
</div>
<div class="row">
<div class="small-12 columns email-field">
<input type="email" name="email" required id="right-label" placeholder="E-mail Address">
<small class="error">An email address is required.</small> </div>
</div>
<div class="row">
<div class="small-12 columns">
<input type="text" name="subject" required id="right-label" placeholder="Subject">
<small class="error">A subject is required.</small>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<textarea name="message" placeholder="Your Message Here" rows="4" required></textarea>
<small class="error">A message is required.</small> </div>
</div>
</div>
</div>
<br/>
<button type="submit" name="submit" value="submit">Submit</button>
<button type="reset">Reset</button>
</form>
<br/>
<div class="success_message">
<h3>Thank you for your message!</h3>
<p>Your email has been sent successfully and I appreciate you getting in touch with me. I will be sending a reply soon.</p>
</div>
<script>
$(document).ready(function() {
if(window.location.hash == '#hashtag') {
$('.success_message').show();
$("html, body").animate({ scrollTop: $('#theForm').offset().top }, 1000);
}
});</script>
You never bothered fencing off your code to check if a form submission was actually performed, so the code will fire EVERY time the page is loaded. You'd want something at least like:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... handle form ...
}
They're required on the browser side, but you have no server-side validation. Older browsers that don't respect HTML5's required attribute, bots, etc. will happily submit all day long.
At its simplest, just check that there's data in each field:
$to = 'design#carolbarone.com' ;
$subject = $_POST['subject'] ;
$name = $_POST['name'] ;
$email = $_POST['email'] ;
$text = $_POST['message'] ;
$message = "From: $name \nEmail: $email \nMessage: $text \n";
if($subject && $name && $email && $text) {
$sent = mail($to, $subject, $message) ;
...
You'd want to do more validation (like making sure $email is a valid format) but this'll at least prevent blank ones. Of note: your form is vulnerable to header injection. Using a proper library like SwiftMailer will make coding email easier as well as protecting you from malicious spambots somewhat.
As Marc B notes, by including the mailing code on the same page as the form, you're firing it whenever someone accesses that page. Typically, your POST handling should be in a different file/route.

Prevent bootstrap modal from closing after form submit

I have searched all over the net and did find some solutions but they all used JS or AJAX and helped to an extent only. I am new to PHP and have no clue about AJAX so if someone here could provide me with a solution using PHP & HTML or at most JS.
I have a very simple subscription form inside a bootstrap 3 modal in the footer section of my client's website. The PHP for it verifies that the subscriber is using their official or company email address only to subscribe and some other common/simpler validations.
The form is working great but the issue is that as soon as the person clicks on submit the modal closes and the user doesn't get to see the success or failure message until they reopen the modal from the trigger button. I want the modal to stay open even after the user submits the form and display whether the form submission was a success or not. I hope I was able to explain my issue properly. Here's my HTML & PHP for your reference:
HTML:
<div id="footer">
<div class="container">
<div class="col-md-6">
<div id="SubscribeModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">✕</button>
</div>
<div class="modal-body">
<?php include('subscribe.php') ?>
</div>
<div class="modal-footer"></div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dalog -->
</div><!-- /.modal -->
<a data-toggle="modal" href="#SubscribeModal" class="text-muted">Subscribe</a>
</div>
</div>
</div>
PHP:
<?php
if(isset($_POST['subscribe'])){
/* Configuration */
$subject = 'Please subscribe me to your Risk Alerts. Thank you.'; // Set email subject line here
$mailto = 'xyz#company.com'; // Email address to send form submission to
/* END Configuration */
if(empty($_POST['firstname'])){
$error = "Please add your first name";
}elseif(empty($_POST['lastname'])){
$error = "Please add your last name";
}elseif(empty($_POST['email'])){
$error = "Please add your business email";
}else{
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
// HTML for email to send submission details
$body = "
<br>
<p>The following information was submitted through the contact form on your website:</p>
<p><b>Name</b>: $firstname $lastname<br>
<b>Email</b>: $email<br>
";
$headers = "From: $firstname $lastname <$email> \r\n";
$headers .= "Reply-To: $email \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = "<html><body>$body</body></html>";
//build list of not allowed providers as lowercase
$NotAllowedClients = array("aol","applemail","comcast","entourage","gmail","hotmail","outlook");
preg_match_all('/\#(.*?)\./',$email,$clientarr);
$client = strtolower($clientarr[1][0]);
if(in_array($client,$NotAllowedClients)){
//Failed
$notice = "<div class=\"row-fluid\">
<div class=\"span12\">
<h3>Subscription Failed!</h3>
<p>Please use an official/company email address to subscribe. Try again</p>
</div>
</div>";
}else{
//Passed
//echo $message;
mail($mailto, $subject, $message, $headers);
$notice = "<div class=\"row-fluid\">
<div class=\"span12\">
<h3>Subscription successful!</h3>
<p>Thank you for taking the time to subscribe to our weekly Risk Alerts.</p>
</div>
</div>";
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Risk Alerts</title>
</head>
<body>
<?php
if(isset($notice)){
echo $notice;
}else{
//Show error for missing field
if(isset($error)){echo $error;}
?>
<div class="thumbnail center well well-small text-center">
<form id="subscription" method="post" action="" class="validate" novalidate>
<div class="row">
<div class="col-xs-6 col-md-6">
<input type="text" name="firstname" value="" class="form-control input-md" placeholder="your first name" />
</div>
<div class="col-xs-6 col-md-6">
<input type="text" name="lastname" value="" class="form-control input-md" placeholder="your last name" />
</div>
</div><p></p>
<input type="text" value="" name="email" class="form-control" placeholder="your email address" required /><br />
<div class="clear">
<input type="submit" value="Subscribe" name="subscribe" class="btn btn-md btn-primary button" />
</div>
</form>
</div>
<?php
}
?>
</body>
</html>
I haven't check your actual PHP but assuming it works, I would submit the form with ajax and process the response.
So, try the following:
Add an ID to your modal content:
<div class="modal-body" id="modal_content">
<?php include('subscribe.php') ?>
</div>
Then change your submit button to this :
Subscribe
Then add this jquery to the bottom of your form page (replace DIRECT_URL_TO_SUBSCRIBE with the correct url):
jQuery(function ($){
$('#submit_button').click(function(){
var post_url = 'DIRECT_URL_TO_SUBSCRIBE.php';
$.ajax({
type : 'POST',
url : post_url,
data: $('#subscription').serialize(), //ID of your form
dataType : 'html',
async: true,
beforeSend:function(){
//add a loading gif so the broswer can see that something is happening
$('#modal_content').html('<div class="loading"><img scr="loading.gif"></div>');
},
success : function(data){
$('#modal_content').html(data);
},
error : function() {
$('#modal_content').html('<p class="error">Error in submit</p>');
}
});
})
});
I was trying to figure out a similar issue so I'll leave this for future googles.
Add to PHP:
<?php
$keepOpen="";
if(isset($notice)){
$keepOpen="<script> $('#SubscribeModal').modal('show'); </script>";
Add to HTML:
<?php echo $keepOpen; ?>
Hi this works,
**data-backdrop="static"**
add that to bootstrap modal class. That should solve the issue for you.
<button type="button" data-backdrop="static" data-toggle="modal"
data- target="#yourID">Subscribe</button>

Categories