I have created a form and I want to mail the form data using PHPMailer. What can I do?
My contact.html file:
<script src="../../Scripts/Custom/contact.js"></script>
<div class="contact-container">
<div class="form-container">
<p class="contactus-heading">Contact us</p>
<div class="inner-form-container">
<div class=" form-row "><input type="text" id="name" class="contact-form-text" placeholder="Your Name here" name="name" /></div>
<div class="form-row"><input type="email" id="email" class="contact-form-text" placeholder="Email" name="email" /></div>
<div class=" form-row"><input type="text" id="phone" class="contact-form-text" placeholder="Phone Number" name="phone" /></div>
<div class="form-row"><textarea class="contact-form-text" id="body" placeholder="your message here" name="message"></textarea></div>
<div class="form-row buttons">
<input type="submit" onclick="sendEmail()" name="btn-send" class="send-btn contact-form-btn" value="send" />
</div>
</div>
</div>
</div>
My Contact.js file:
function sendEmail() {
var name = $('#name')[0].value;
var email = $('#email')[0].value;
var phone = $('#phone')[0].value;
var body = $('#body')[0].value;
if (isNotEmpty(name, email, phone, body)) {
debugger;
$.ajax({
url: '../../Pages/Shared/mail.php',
type: 'POST',
name: name,
email: email,
phone: phone,
body: body,
success: function (response) {
console.log(response);
}, error: function (e) {
console.log(e);
}
});
}
}
function isNotEmpty(name, email, phone, body) {
debugger
if (name != "" && email != "" && phone != "" && body != "") {
return true;
} else {
console.log('some fields are empty');
return false
}
}
My mail.php file:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
if(isset($_POST['name']) && isset($_POST['email'])){
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$body=$_POST['body'];
require_once "../../Libraries/PHPMailer.php"
require_once "../../Libraries/SMTP.php"
require_once "../../Libraries/Exception.php"
$mail = new PHPMailer();
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.gmail.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'mailhere'; // SMTP username
$mail->Password = 'password here'; // SMTP password
$mail->SMTPSecure = 'TLS'; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587;
$mail->isHTML(true);
$mail->setFrom($email, $name);
$mail->addAddress('mailhere'); // Add a recipient
$mail->Subject = 'It is a subject';
$mail->addReplyTo('mailhere');
$mail->Body = $body;
if($mail->send())
$response="Email is sent!";
else
$response= "Something went wrong :<br><br>".$mail->ErrorInfo;
exit(json_encode(array("response" =>$response)));
}
?>
When I filled the information in the form, The error I got is:
The request sent to the Web server used an HTTP verb that is not allowed by the module configured to handle the request. \tA request was sent to the server that contained an invalid HTTP verb. \tThe request is for static content and contains an HTTP verb other than GET or HEAD. \tA request was sent to a virtual directory using the HTTP verb POST and the default document is a static file that does not support HTTP verbs other than GET or HEAD.
Related
I have searched for this answer for the past few days and have tried everything to make this work so please help.
I had made a contact form but I will only receive an email if I use the email that the form is submitting to. If I use any other email it will still said the email is sent but when I check my inbox there is nothing there. Same as my junk and sent folders. Although if I complete the form with my email I will get an email in my inbox. (So the form email and the email address submitting to is the same).
This is my index.php
<!DOCTYPE html>
<html>
<head>
<title>Send an Email</title>
</head>
<body>
<center>
<h4 class="sent-notification"></h4>
<form id="myForm">
<h2>Send an Email</h2>
<label>Name</label>
<input id="name" type="text" placeholder="Enter Name">
<br><br>
<label>Email</label>
<input id="email" type="text" placeholder="Enter Email">
<br><br>
<label>Subject</label>
<input id="subject" type="text" placeholder=" Enter Subject">
<br><br>
<p>Message</p>
<textarea id="body" rows="5" placeholder="Type Message"></textarea>
<br><br>
<button type="button" onclick="sendEmail()" value="Send An Email">Submit</button>
</form>
</center>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function sendEmail() {
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
body: body.val()
}, success: function (response) {
$('#myForm')[0].reset();
$('.sent-notification').text("Message Sent Successfully.");
}
});
}
}
This is my sendEmail.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
if(isset($_POST['name']) && isset($_POST['email'])){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$body = $_POST['body'];
require 'vendor/autoload.php';
$mail = new PHPMailer();
//Server settings
$mail->isSMTP(); //Send using SMTP
$mail->Host = 'smtp.mail.yahoo.com'; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = 'atouchof.beauty#yahoo.com'; //SMTP username
$mail->Password = 'aaa'; //SMTP password
$mail->SMTPSecure = 'tsl'; //Enable implicit TLS encryption
$mail->Port = 587; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
$mail->isHTML(true); //Set email format to HTML
$mail->setFrom($email, $name);
$mail->addAddress("atouchof.beauty#yahoo.com");
$mail->Subject = ("$email ($subject)");
$mail->Body = $body;
if($mail->send()){
$status = "success";
$response = "Email is sent!";
}
else
{
$status = "failed";
$response = "Something is wrong: <br>" . $mail->ErrorInfo;
}
exit(json_encode(array("status" => $status, "response" => $response)));
}
?>
This may sound confusing so please ask any questions if you don't understand.
Two problems. Firstly you're forging the from address, which is very probably the cause of your problems. This is well documented, and I recommend following the advice given in the PHPMailer contact form example.
A minor issue is that you're setting this to a non-existent value:
$mail->SMTPSecure = 'tsl';
That should be:
$mail->SMTPSecure = 'tls';
You can call multiple times:
$mail->AddAddress('emailONE#gmail.com', 'Juan');
$mail->AddAddress('emailTWO#gmail.com', 'Pepe');
I recommend use https://mailtrap.io/ for testing emails
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.
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]*\r\n)?[ \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]*\r\n)?[ \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.";
}
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") . "\n"; //no exception
echo verify(null). "\n" //exception
} catch (Exception $e) { //sees exception present and catches it for processing
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
I have this simple bootstrap form that i run on my localhost, it accepts name email and message and a custom captcha in a form of a math question; On submit i used jquery ajax to fetch the data to emailme.php that contains the phpmailer code.. My problem is, no email was sent even if there's no error and the network status is 200 and i can also see this:
http://localhost/emailme.php?name=myname&email=myemail#gmail.com&message=test
however it works if i just use the phpmailer stand alone code with fixed values. how can i make it work?
HTML:
<form id="emailme" method="post">
<div class="form-group">
<input type="text" class="form-control" name="name" id="name" placeholder="e.g. John Doe">
<span id="err_name" class="text-danger"></span>
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" id="email" placeholder="e.g. example#domain.com">
<span id="err_email" class="text-danger"></span>
</div>
<div class="form-group">
<textarea name="message" id="message" cols="30" rows="10" class="form-control" placeholder="Your message"></textarea>
<span id="err_message" class="text-danger"></span>
</div>
<div class="form-group">
<label for="human">5 + 2 = ?</label>
<input type="text" id="human" name="human" class="form-control" placeholder="Your Answer">
<span id="err_human" class="text-danger"></span>
</div>
<input type="submit" class="btn btn-primary btn-sm" value="Send">
</form>
JQUERY:
$("#emailme").on('submit',function(e){
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var human = $("#human").val();
var emailRegex = /(.+)#(.+)\.(com|edu|org|etc)$/g;
if(name!==''&&email!==''&&message!==''&&human!==''){
if(email.match(emailRegex)){
if(human==7){
$.ajax({
url:'emailme.php',
typ:'post',
data:{name:name,email:email,message:message},
success:function(response){
console.log(response);
$("#mail-status").html(response);
$("#emailme")[0].reset();
},
error:function(XMLHttpRequest,textStatus,errorThrown){
console.log(textStatus+errorThrown);
}
});
}
else{
$("#mail-status").html("unable to submit form, you're not human");
}
}
else{
$("#err_email").append("Invalid email format");
}
}
else if(name==''){
$("#err_name").append("Name cannot be empty");
}
else if(email==''){
$("#err_email").append("Email cannot be empty");
}
else if(message==''){
$("#err_message").append("Message cannot be empty");
}
else if(human==''){
$("#err_human").append("Please answer the security question");
}
});
PHP:
<?php
date_default_timezone_set('Etc/UTC');
require 'phpmailer/PHPMailerAutoload.php';
// Set the email address submissions will be sent to
$email_address = 'myemail#gmail.com';
// Set the subject line for email messages
$subject = 'Test email from localhost using PHPMailer';
// Check for form submission
if(isset($_POST['name'], $_POST['email'], $_POST['message'])){
//Create a new PHPMailer instance
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "myemail#gmail.com";
$mail->Password = "mypassword";
$mail->setFrom($_POST['email'], $_POST['name']);
$mail->addAddress($email_address, 'myname');
$mail->Subject = $subject;
$mail->Body = 'From:'.$_POST['name'].'(' . $_POST['email'] . ')'.'<p><b>Message</b><br/>' . $_POST['message'] . '</p>';
$mail->AltBody = 'This is a plain-text message body';
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
}
?>
I am currently working on a quote form. After submitting the form, there was an email set to send submitted record back to client as copy. However, as I was using Mandrill for transaction emails, it's no longer free. I don't want to use any paid service and am now looking to send the same email using PHPMailer. I am finding it difficult to understand to call php to send email. Any help? I am open for options. All I want to send email after form submits.
email.js
function finalize_things(data, order_id){
//posting data to the server side page
$.post(window.location.origin+'/post/', data,function(response){
if(response == 'success'){
console.log(response);
send_email(order_id, data.email, data.firstname, data.project_details, data.file_names);
} else {
console.log(response);
alert('order not placed.');}
});
}
function send_email(order_id, email, firstname, project_details, file_names){
var html_message = "message here"
data = {
"key": "xxxxxxxxx",
"message": {
"html": html_message,
"text": "",
"subject": "Your subject",
"from_email": "test#test.com",
"from_name": "Company name",
"to": [{
"email": email,
"name": firstname
}
]},
"async": false
};
$.ajax({url: 'https://mandrillapp.com/api/1.0/messages/send.json',
type: 'POST',
data: data,
success: function(resp){
console.log(resp); }
});
PHPMAILER Code:
include_once '/../../PHPMailer/cms_db.php';
require_once '/../../PHPMailer/PHPMailerAutoload.php';
require_once '/../../PHPMailer/config.php';
if (isset($_POST["email"]) && !empty($_POST["email"])) {
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Host = $smtp_server; // Specify main and backup SMTP servers
$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("companyemail#xyz.com", "Company Name");
$mail->addAddress($email, $firstname); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$bodyContent = "test message";
$mail->Subject = "Your Quote ID";
$mail->Body = $bodyContent;
$mail->AltBody = $bodyContent;
if(!$mail->send()) {
echo "Message could not be sent.";
$error = '<div class="alert alert-danger"><strong>Mailer Error: '. $mail->ErrorInfo.'</strong></div>';
} else {
$error = '<div class="alert alert-success"><strong>Message has been sent</strong></div>';
}
}
So, if you don't want to use external services like gmail... You need to set up your own mail server (postfix, sendmail etc.) Please note, that webservers very often has potfix onboard (httpd + php + mysql + postfix) already.
Has your hosting postfix already? Check this by using standard mail function, php script like :
<?php
$to = 'yourmail#gmail.com';
$subject = 'test subj';
$mail_body = 'test body';
mail($to, $subject, $mail_body);
?>
If it works -- write your own script based on this code or use phpmailer (it has settings for local mail daemon)
PS PHPMailer can send mail via extenal webserver, like gmail https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps (key line here: $mail->isSMTP();) or via local server, such as postfix -- see example here -- key line is $mail->isSendmail();
and your current code snippet is for using EXTERNAL service, not for LOCAL!
Changes in your js this line:
$.ajax({url: 'https://mandrillapp.com/api/1.0/messages/send.json',
to:
$.ajax({url: 'http://yourserver.tld/send_phpmailer.php',
And use something like this in send_phpmailer.php:
<?php
////// Part 1. Set up variables
$key = $_POST['key']; // need for mandrill, you can omit this
$html = $_POST['message']['html'];
$text = $_POST['message']['text'];
$subject = $_POST['message']['subject'];
$from_email = $_POST['message']['from_email'];
$from_name = $_POST['message']['from_name'];
$to_email = $_POST['message']['to']['email'];
$to_name = $_POST['message']['to']['name'];
////// Part 2. Including PHPMailer
include_once '/../../PHPMailer/cms_db.php';
require_once '/../../PHPMailer/PHPMailerAutoload.php';
require_once '/../../PHPMailer/config.php';
////// Part 3. Sending letter by PHPMailer
$mail = new PHPMailer;
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "username#gmail.com";
$mail->Password = "yourpassword";
//Set who the message is to be sent from
$mail->setFrom( $from_email, $from_name);
//Set an alternative reply-to address
//$mail->addReplyTo('replyto#example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress($to_email, $to_name);
//Set the subject line
$mail->Subject = $subject;
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML($html);
//Replace the plain text body with one created manually
$mail->AltBody = $text;
//Attach an image file
//$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
<?php
include ('config.php');
if(isset($_POST['submit']))
{
$name=mysqli_real_escape_string($conn,$_POST['name']);
$email=mysqli_real_escape_string($conn,$_POST['email']);
$phone=mysqli_real_escape_string($conn,$_POST['phone']);
$msg=mysqli_real_escape_string($conn,$_POST['msg']);
$sql="insert into contact(`name`,`email`,`phone`,`msg`) values('$name','$email','$phone','$msg')";
// $result=mysqli_query($conn,$sql);
if(mysqli_query($conn, $sql)){
$to='akhilsai.innovkraft#gmail.com'; // Receiver Email ID, Replace with your email ID
$subject='Form Submission';
$message="Name :".$name."\n"."Phone :".$phone."\n"."Wrote the following :"."\n\n".$msg;
$headers="From: ".$email;
$sentmail=swiftmail($to, $subject, $message, $headers);
header('localtion:index.html');
}
else{
echo "ERROR:";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Feedback Form</title>
</head>
<body>
<div class="main">
<div class="info">Give Your Feedback!</div>
<form action="#" method="post" name="form" class="form-box">
<label for="name">Name</label><br>
<input type="text" name="name" class="inp" placeholder="Enter Your Name" required><br>
<label for="email">Email ID</label><br>
<input type="email" name="email" class="inp" placeholder="Enter Your Email" required><br>
<label for="phone">Phone</label><br>
<input type="tel" name="phone" class="inp" placeholder="Enter Your Phone" required><br>
<label for="message">Message</label><br>
<textarea name="msg" class="msg-box" placeholder="Enter Your Message Here..." required></textarea><br>
<input type="submit" name="submit" value="Send" class="sub-btn">
</form>
</div>
</body>
</html>
i try this coding in my own way
<?php
include ('config.php');
if(isset($_POST['submit']))
{
$name=mysqli_real_escape_string($conn,$_POST['name']);
$email=mysqli_real_escape_string($conn,$_POST['email']);
$phone=mysqli_real_escape_string($conn,$_POST['phone']);
$msg=mysqli_real_escape_string($conn,$_POST['msg']);
$sql="insert into contact(`name`,`email`,`phone`,`msg`) values('$name','$email','$phone','$msg')";
// $result=mysqli_query($conn,$sql);
if(mysqli_query($conn, $sql)){
$to='akhilsai.innovkraft#gmail.com'; // Receiver Email ID, Replace with your email ID
$subject='Form Submission';
$message="Name :".$name."\n"."Phone :".$phone."\n"."Wrote the following :"."\n\n".$msg;
$headers="From: ".$email;
$sentmail=swiftmail($to, $subject, $message, $headers);
header('localtion:index.html');
}
else{
echo "ERROR:";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Feedback Form</title>
</head>
<body>
<div class="main">
<div class="info">Give Your Feedback!</div>
<form action="#" method="post" name="form" class="form-box">
<label for="name">Name</label><br>
<input type="text" name="name" class="inp" placeholder="Enter Your Name" required><br>
<label for="email">Email ID</label><br>
<input type="email" name="email" class="inp" placeholder="Enter Your Email" required><br>
<label for="phone">Phone</label><br>
<input type="tel" name="phone" class="inp" placeholder="Enter Your Phone" required><br>
<label for="message">Message</label><br>
<textarea name="msg" class="msg-box" placeholder="Enter Your Message Here..." required></textarea><br>
<input type="submit" name="submit" value="Send" class="sub-btn">
</form>
</div>
</body>
</html>
I am new to PHP coding. I have created a Customer form, followed by send e-mail function. When a Customer submits data (including E-Mail and password) he should receive a confirmation e-mail with User ID (same as entered E-Mail Id) and entered Password.
At this moment, with my current code, when a Customer submits the form, database gets updated, but no e-mail is send to the user. Can anyone point out what needs to be changed to ensure that send e-mail function works correctly.
<!DOCTYPE html>
<html>
<head>
<title>Registration Desk</title>
</head>
<body>
<div class="form">
<form id="contactform" action="reg_submit.php" method="post">
<p class="contact"><label for="name">Name</label></p>
<input id="name" name="name" placeholder="First and last name" required="" tabindex="1" type="text">
<p class="contact"><label for="add">Address</label></p>
<textarea id="add" name="add" style="width:85%; height:60%; margin-top:1%" required=""></textarea>
<fieldset>
<label>Birthday</label>
<input type="date" name="dob" value="yyyy-mm-dd" required="">
</fieldset>
<label>I am</label> <br><br>
<input type="radio" name="sex" value="male" >Male
<input type="radio" name="sex" value="female">Female
<p class="contact"><label for="email">Email</label></p>
<input id="email" name="email" class="field" placeholder="Please enter a valid emailid" required="" type="email">
<p class="contact"><label for="password">Create a password</label></p>
<input type="password" id="password" name="password" required="">
<p class="contact"><label for="repassword">Confirm your password</label></p>
<input type="password" id="repassword" name="repassword" required="">
<br><br>
<p class="contact"><label for="phone">Mobile phone</label></p>
<input id="phone" name="phone" placeholder="phone number" required="" type="text"> <br>
<input class="buttom" name="submit" id="submit" tabindex="5" value="Sign me up!" type="submit">
</form>
</div>
</div>
</body>
</html>
<?php
error_reporting( 0);
$connect=mysqli_connect("localhost","wbtecqoj_saltee","webuildtec1","wbtecqoj_salteegroup");
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if( $_POST["password"]!= $_POST["repassword"])
{
?>
<script type="text/javascript">
alert("password miss matched!!!.");
history.back();
</script>
<?php
}
if($_POST["name"] && $_POST["add"] && $_POST["phone"] && $_POST["email"] && $_POST["password"] && $_POST["dob"] )
{
$insert="INSERT INTO `db`.`new_user` (`id`, `name`, `add`, `contact`, `email`, `pass`, `dob`, `gender`,`code`) VALUES (NULL, '$_POST[name]', '$_POST[add]', '$_POST[phone]', '$_POST[email]', '$_POST[password]', '$_POST[dob]', '$_POST[sex]', 'SAL1000000')";
if(!mysqli_query($connect,$insert))
{
echo die('Error: ' . mysqli_error($connect));
}
else
{
$to=$_POST['email'];
$from= "admin#wbtec.in";
$subject="Welcome to xyz Group";
$message="Welcome " . $_POST['name'] . "Dear Customer,
Your Card Number is " .$Ccode.$cookieId. " User id -" . $_POST['email'] . "Your Password -" . $_POST['password'].
"Thanking You,
Customer Care,";
$header = "From" .$from;
if(isset($_POST['btnSend']))
{
$res = mail($to,$subject,$message,$header);
if($res)
{
echo 'Message send';
}
else
{
echo 'msg not send';
}
}
}}
mysqli_close($connect);
?>
Remove the
if(isset($_POST['btnSend']))
{
}
You are checking for
if(isset($_POST['btnSend']))
But your form doesn't contain an input named btnSend, you should be able to remove that if statement altogether
I suggest you to use PHPMailer from
http://sourceforge.net/projects/phpmailer/
With the PHPMailer class you can specify the outgoing SMTP server and authenticate with it properly. Here is an example how I used it:
<?php
require("class.phpmailer.php");
class Mailer
{
function send($email, $subject, $body, $attachment1)
{
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail->Host = "mail.xyz.com"; // your SMTP servers
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "authname"; // SMTP username
$mail->Password = "authpassword"; // SMTP password
$mail->From = "info#xyz.com";
$mail->FromName = "info#xyz.com";
$mail->AddAddress($email);
$mail->WordWrap = 50; // set word wrap
if ($attachment1 != "") {
$mail->AddAttachment($attachment1); // attachment1
}
$mail->IsHTML(false); // send as HTML
$mail->Subject = $subject;
$mail->Body = $body;
if(!$mail->Send())
{
return -1;
}
else
{
return 0;
}
}
}
?>
Hope that helps!
u have to download php mailer library which have to files
PHP mailer
class.phpmailer.php and other class.smtp.php then add this file at same directory which have php code which is shown below..
<?PHP
require_once('class.phpmailer.php');
if('POST' == $_SERVER['REQUEST_METHOD']) {
// process the form here
$subject = "This is subject testing1";
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->IsHTML(true); // send as HTML
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port
//$mail->Username = "gmailusername"; // GMAIL username
//$mail->Password = "password"; // GMAIL password
$mail->From = 'email id';
$mail->FromName = "FrontName";
$mail->Subject = $subject;
$mail->Body = "this is html body"; //HTML Body
$emailId='email id';
$emails = explode(",",$emailId);
foreach($emails as $email)
$mail->AddAddress($email);
if($mail->Send()){
echo "Message sent successfully";
}else{
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
?>
<form action="" method="post">
<input type="submit" name='button1'value="sent mail" />
</form>