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.
I am trying to build an inquiry form and send the data to my email using PHPMailer. I am receiving the data which is submitted through the form but I am not able to send a confirmation to the customer who filled the form. So far this is my form:
<form class="myForm" action="" id="iForm" method="POST">
<input type="text" id="Name" placeholder="Name" required>
<input type="email" id="Email" placeholder="Email" required>
<input type="tel" id="Phone" placeholder="Phone Number" required>
<input type="text" id="Date" placeholder="Schedule a call" required>
<textarea id="Message" rows="5" placeholder="Your Message" required></textarea>
<div class="form-group">
<button type="submit" class="btn cbtn">SUBMIT</button>
</div>
</form>
Passing the data from the submitted form
$("#iForm").on('submit', function(e) {
e.preventDefault();
var data = {
name: $("#Name").val(),
email: $("#Email").val(),
phone: $("#Phone").val(),
date: $("#Date").val(),
message: $("#Message").val()
};
if ( isValidEmail(data['email']) && (data['name'].length > 1) && (data['date'].length > 1) && (data['message'].length > 1) && isValidPhoneNumber(data['phone']) ) {
$.ajax({
type: "POST",
url: "php/appointment.php",
data: data,
success: function() {
$('.success.df').delay(500).fadeIn(1000);
$('.failed.df').fadeOut(500);
}
});
} else {
$('.failed.df').delay(500).fadeIn(1000);
$('.success.df').fadeOut(500);
}
return false;
});
Checking for valid email address
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
Checking for a valid phone number
function isValidPhoneNumber(phoneNumber) {
return phoneNumber.match(/[0-9-()+]{3,20}/);
}
This is the code which I am using from PHPMailer:
$_name = $_REQUEST['name'];
$_email = $_REQUEST['email'];
$_phone = $_REQUEST['phone'];
$_date = $_REQUEST['date'];
$_message = $_REQUEST['message'];
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->Username = "office#myhost.co.uk";
$mail->Password = "********";
$mail->Host = "myhost.co.uk";
$mail->setFrom('office#myhost.co.uk', 'Alex');
$mail->addAddress('me#gmail.com', 'Alex');
$mail->isHTML(true);
$mail->Subject = 'New inquiry from CC';
$mail->Body = <<<EOD
<strong>Name:</strong> $_name <br>
<strong>Email:</strong> $_email <br> <br>
<strong>Phone:</strong> $_phone <br>
<strong>Booking Date:</strong> $_date <br>
<strong>Message:</strong> $_message <br>
I've tried using this, making another instance of PHPMailer and Send the email to the customer with the email they provided.
if($mail->Send()) {
$autoRespond = new PHPMailer();
$autoRespond->setFrom('office#myhost.co.uk', 'Alex');
$autoRespond->AddAddress($_email);
$autoRespond->Subject = "Autorepsonse: We received your submission";
$autoRespond->Body = "We received your submission. We will contact you";
$autoRespond->Send();
}
I've tried a few online "solutions" to this with no success. Any ideas ?
I finally found the solution of my issue. Basically everything above is correct the only thing which I missed was pass the SMTP parameters again to the new instance of PHPMailer. So now the last piece of code which caused the issue looks like that:
if($mail->Send()) {
$autoRespond = new PHPMailer();
$autoRespond->IsSMTP();
$autoRespond->CharSet = 'UTF-8';
$autoRespond->SMTPDebug = 0;
$autoRespond->SMTPAuth = TRUE;
$autoRespond->SMTPSecure = "tls";
$autoRespond->Port = 587;
$autoRespond->Username = "office#myhost.co.uk";
$autoRespond->Password = "********";
$autoRespond->Host = "myhost.co.uk";
$autoRespond->setFrom('office#myhost.co.uk', 'Alex');
$autoRespond->addAddress($_email);
$autoRespond->Subject = "Autorepsonse: We received your submission";
$autoRespond->Body = "We received your submission. We will contact you";
$autoRespond->Send();
}
Thank you for the help everyone.
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 have been created simple mail sending from localhost using php,
Her is the code:
HTML:
<form method="post" action="email.php">
Email: <input name="email" id="email" type="text" /><br />
Message:<br />
<textarea name="message" id="message" rows="15" cols="40"></textarea><br />
<input type="submit" value="Submit" />
</form>
EMAIL.PHP:
<?php
require_once('class.phpmailer.php');
$mail->MsgHTML($body);
$body ='A sample email';
$mailer->IsSMTP();
$mailer->SMTPDebug = 0;
$mailer->SMTPAuth = true;
$mailer->SMTPSecure = 'ssl';
$mailer->Port = 465;//587;
$mailer->Host = 'smtp.gmail.com';
$mailer->Username = 'YYYYYYYYYY#gmail.com';
$mailer->Password = 'XXXXXXXXX';
?>
when run this code,
following error displayed,
Fatal error: Call to a member function MsgHTML() on a non-object online 6
note: where is got phpmailer.php source code from this link
I m new to php, but i want to know, particular this section.
Can anyone help me to fix this,
Thanks in advance,
Perhaps $mail is not instantiated, and spelled wrong (did you mean $mailer?). Also, you should set $body before MsgHTML($body). From your link, you may want to add this
$mailer = new PHPMailer;
and make changes like so:
$mailer = new PHPMailer;
$body ='A sample email';
//$mail->MsgHTML($body);
$mailer->MsgHTML($body);
$mailer->IsSMTP();
...
Here is an example of an HTML-form and PHPMailer:
HTML
<form method="post" action="email.php">
Email: <input name="email" id="email" type="text" /><br />
Message:<br />
<textarea name="message" id="message" rows="15" cols="40"></textarea><br />
<input type="submit" value="Submit" />
</form>
mail.php
<?php
// $email and $message are the data that is being
// posted to this page from our html contact form
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;
require_once('class.phpmailer.php');
$mail = new PHPMailer();
// set mailer to use SMTP
$mail->IsSMTP();
// As this email.php script lives on the same server as our email server
// we are setting the HOST to localhost
$mail->Host = "localhost"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
// When sending email using PHPMailer, you need to send from a valid email address
// In this case, we setup a test email account with the following credentials:
// email: send_from_PHPMailer#bradm.inmotiontesting.com
// pass: password
$mail->Username = "send_from_PHPMailer#bradm.inmotiontesting.com"; // SMTP username
$mail->Password = "password"; // SMTP password
// $email is the user's email address the specified
// on our contact us page. We set this variable at
// the top of this page with:
// $email = $_REQUEST['email'] ;
$mail->From = $email;
// below we want to set the email address we will be sending our email to.
$mail->AddAddress("bradm#inmotiontesting.com", "Brad Markle");
// set word wrap to 50 characters
$mail->WordWrap = 50;
// set email format to HTML
$mail->IsHTML(true);
$mail->Subject = "You have received feedback from your website!";
// $message is the user's message they typed in
// on our contact us page. We set this variable at
// the top of this page with:
// $message = $_REQUEST['message'] ;
$mail->Body = $message;
$mail->AltBody = $message;
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
?>
i have code for send email to my email
but if i press ok i get can not send email to **#hotmail.com
i work on linux server (fedora), and i don not change any settings
my mail.html file is
<html>
<head><title>Mail sender</title></head>
<body>
<form action="mail.php" method="POST">
<b>Email</b><br>
<input type="text" name="email" size=40>
<p><b>Subject</b><br>
<input type="text" name="subject" size=40>
<p><b>Message</b><br>
<textarea cols=40 rows=10 name="message"></textarea>
<p><input type="submit" value=" Send ">
</form>
</body>
</html>
and my email.php file is :
<html>
<head><title>PHP Mail Sender</title></head>
<body>
<?php
# Retrieve the form data
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
# Sends mail and report success or failure
if (mail($email,$subject,$message)) {
echo "<h4>Thank you for sending email</h4>";
} else {
echo "<h4>Can't send email to $email</h4>";
}
?>
</body>
</html>
please try help me
Best if you use a dedicated script for sending emails. Such as PHPMailer which gives you various config options including SMTP:
// Send Mail
$mail = new PHPMailer(); // initiate
$mail->IsSMTP(); // use SMTP
// SMTP Configuration
$mail->SMTPAuth = true; // set SMTP
$mail->Host = "myhost"; // SMTP server
$mail->Username = "email#email.com";
$mail->Password = "password";
$mail->Port = 465; // change port is required