I am trying to email a basic contact form using PHPMailer.
This form works for me:
<?php
$first_name = $_POST['first-name'];
$last_name = $_POST['last-name'];
$email = $_POST['email'];
$message = nl2br($_POST['message']);
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = ''; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ''; // SMTP username
$mail->Password = ''; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;
$mail->addReplyTo( $email, $first_name );
$mail->addAddress( $email, $first_name );
$mail->addAddress( 'blah#fake.org', 'Staff' );
$mail->From = 'blah#fake.org';
$mail->FromName = 'Staff';
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Hotel Room Request';
$mail->Body = $message;
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
if(!$mail->send()) {
header('location: a_url_here');
} else {
header('location: a_url_here');
}
Now, I'm trying to combine it with error-checking. Don't know how to combine it and still make it work. This is what I have so far, and it blanks out upon submittal. I wasn't sure where to put check_input function, so I put it in the else part at the bottom. How do I make this form functional so not only does it validate user's input but email it out?
<?php
$first_name = check_input($_POST['first-name'], "Please enter your name");
$last_name = check_input($_POST['last-name'], "Please enter your last name");
$email = check_input($_POST['email'], "Please enter your email address");
$message = check_input(nl2br($_POST['message']), "Please enter your message");
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = ''; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ''; // SMTP username
$mail->Password = ''; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;
$mail->addReplyTo( $email, $first_name );
$mail->addAddress( $email, $first_name );
$mail->addAddress( 'blah#fake.org', 'Staff' );
$mail->From = 'blah#fake.org';
$mail->FromName = 'Staff';
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Hotel Room Request';
$mail->Body = $message;
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
if(!$mail->send()) {
header('location: a_url_here');
} else {
function check_input($data, $problem = ' ')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
}
?>
Create so-called validator class:
class Validator {
// set of rules for validator
// syntax: <field-name> => '<list-of-rules, joined-with-pipe>',
protected $rules = [
'first-name' => 'required',
'last-name' => 'required',
'message' => 'required',
'email' => 'required|email',
];
// message to show if concrete field-rule failed
// ":field" will be replaced with field actual name
protected $messages = [
'required' => 'Field :field is required',
'nonzero' => 'Field :field must not be zero'
'email' => 'Field :field must represent an emai address'
];
protected $errors;
// call this to validate provided $input
function validate($input) {
$errors = [];
// for each defined field-ruleset
foreach ($this->rules as $field => $rules) {
$rules = explode('|', $rules);
// for each rule
foreach ($rules as $rule)
// call function with name "checkNameofrule"
if (!$this->{"check" . ucfirst($rule)}($input, $field))
// memorize error, if any
$errors[$field][] = $this->error($field, $rule);
}
// validation passed if there are no errors
return !($this->errors = $errors);
}
function errors() {
return $this->errors;
}
function error($field, $error) {
return str_replace(':field', $field, $this->messages[$field]);
}
// check for required fields
function checkRequired($input, $field) {
if (!isset($input[$field]))
return false;
return trim(htmlspecialchars(stripslashes($input[$field]))) != '';
}
// check for valid email
function checkEmail($input, $field) {
return !!preg_match('#.+#[^.]+\..+#', #$input[$field]);
}
// other custom checks
function checkNonzero($input, $field) {
return intval(#$input[$field]) != 0;
}
}
And use it like this:
$validator = new Validator();
// validating...
if (!$validator->validate($_POST)) {
// looks like there are errors in input
echo "<div class=\"errors\">";
echo "<b>Looks like you have errors in input:</b><br />";
foreach ($validator->errors() as $field => $errors) {
foreach ($errors as $error)
echo "<p>{$error}</p>";
}
echo "</div>";
} else {
// input had passed validation, send email...
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
...
if(!$mail->send()) {
header('location: a_url_here');
} else {
header('location: a_url_here');
}
}
You should not validate and render the form in one file. It leads to poor maintainability and mixes responsibilities in a nasty way. Try structuring your project like so:
form.php
validate-and-send.php
The form contains <form action=validate-and-send.php ...><input ....
The other file contains logic for validating and sending. Something like this:
<?php
$email = filter_var($_REQUEST['email'], FILTER_VALIDATE_EMAIL);
if ($email) {
....
}
if (/*all fields valid*/) {
// phpmailer code
} else {
// redirect back to form
}
The tricky part is redirect back to form. You can either redirect with a header and set all valid fields through get-parameters Location form.php?name=validname or you can stuff them in $_SESSION and output them in the form from session.
Taking it one step farther would be submitting via AJAX and responding with the validation result as JSON, for example. So the flow would be like
1. form.submit() -> ajax -> validate-and-send.php
2a. validate-and-send.php -> "OK" -> form.php
2b. validate-and-send.php -> JSON: { errors: [ {reason: "bad name"}, {reason: "bad email"}]}
-> form.php
3. Display what happened with JS.
Related
I have gone through multiple questions like this and nothing seems to fix my problem. I have set the SMTP debug option to 2, checked my credentials (changed to example ones for posting obviously) also checked the smtp server and port, using gmail and tls with port 465. I'm using ajax to submit form data on the click on submit button.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
/* Exception class. */
require '/home/saveyamo/public_html/PHPMailer/src/Exception.php';
/* The main PHPMailer class. */
require '/home/saveyamo/public_html/PHPMailer/src/PHPMailer.php';
/* SMTP class, needed if you want to use SMTP. */
require '/home/saveyamo/public_html/PHPMailer/src/SMTP.php';
$errorMSG = "";
/* NAME */
if (empty($_POST["firstName"])) {
$errorMSG = "<li class='danger'>Your first name is required</<li>";
} elseif (!filter_var($_POST["firstName"], FILTER_VALIDATE_INT) === false) {
$errorMSG = "<li class='danger'>A number is not a valid name</<li>";
} else {
$firstname = filter_var($_POST["firstName"], FILTER_SANITIZE_STRING);
}
if (empty($_POST["lastName"])) {
$errorMSG = "<li class='danger'>Your last name is required</<li>";
} elseif (!filter_var($_POST["lastName"], FILTER_VALIDATE_INT) === false) {
$errorMSG = "<li class='danger'>A number is not a valid name</<li>";
} else {
$lastname = filter_var($_POST["lastName"], FILTER_SANITIZE_STRING);
}
/* EMAIL */
if (empty($_POST["email"])) {
$errorMSG .= "<li class='danger'>Email is required</li>";
} elseif (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
$errorMSG .= "<li class='danger'>Invalid email format</li>";
} else {
$email = $_POST["email"];
}
/*phone*/
/*
if (empty($_POST["phone"])) {
$errorMSG = "<li>Your phone number is required</<li>";
} else if (is_string($_POST["phone"])) {
$errorMSG = "<li>That is not a valid phone number</<li>";
} else if (is_int($_POST["phone"])) {
$phone = $_POST["phone"];
}
*/
function validate_phone_number($phones)
{
// Allow +, - and . in phone number
$filtered_phone_number = filter_var($phones, FILTER_SANITIZE_NUMBER_INT);
// Remove "-" from number
$phone_to_check = str_replace("-", "", $filtered_phone_number);
// Check the lenght of number
// This can be customized if you want phone number from a specific country
if (strlen($phone_to_check) < 10 || strlen($phone_to_check) > 14) {
return false;
} else {
return true;
}
}
if (validate_phone_number($_POST["phone"]) == true) {
$phone = $_POST["phone"];
} elseif (validate_phone_number($_POST["phone"]) == false) {
$errorMSG = "<li class='danger'>That is not a valid phone number, try again. Be sure to include your area code.</li>";
} elseif (empty($_POST["phone"])) {
$errorMSG = "<li class='danger'>Your phone number is required</<li>";
}
/* marina */
if (empty($_POST["marina"])) {
$errorMSG = "<li class='danger'>Your marina is required</<li>";
} else {
$marina = filter_var($_POST["marina"], FILTER_SANITIZE_STRING);
}
/* checkboxes */
$boxes = $_POST["boxes"];
/* MESSAGE */
if (empty($_POST["message"])) {
$errorMSG .= "<li class='danger'>Message is required</li>";
} else {
$message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
}
if (empty($errorMSG)) {
$message = "Name: ".$firstname." ".$lastname."<br />".", Email: ".$email."<br />".", Phone: ".$phone."<br />".", Marina: ".$marina."<br />".", Interests: ".$boxes."<br />".", Message:".$message;
$ok = "<li class='ok'>Awesome! Your message was sent, we will be in touch shortly.</li>";
//echo json_encode(['code'=>200, 'msg'=>$message]);
echo json_encode(['code'=>200, 'msg'=>$ok]);
$to = "john.e.puaoi#gmail.com";
$subject = "Contact";
//mail($to, $subject, $message);
//phpmailer start
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'example#example.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('web#example.com', 'Contact Form');
$mail->addAddress('example#gmail.com'); // Name is optional
$mail->addReplyTo('$email', '$firstname');
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Contact Form Submission';
$mail->Body = '$message';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
//phpmailer end
exit;
}
echo json_encode(['code'=>404, 'msg'=>$errorMSG]);
I am new to PHP and trying to implement Google reCaptcha v2 using PHP and AJAX using either CurlPost() or SocketPost() methods. Currently everything runs fine with file_get_contents() but my provider is going to lock it down soon so I need to refactor my code. Somehow I ran into problem with implementing CurlPost() or SocketPost() - whenever I try to use either of them, nginx responds with 403 stating that Not a POST request (it is hardcoded in one of the else clauses).
What exactly did I overlook with POST? Below are two pieces of code, one is working perfectly with file_get_contents() and second is code in question throwing 403.
Working one
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
require("PHPMailer.php");
require("Exception.php");
require("SMTP.php");
require('recaptcha-master/src/autoload.php');
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$tel = trim($_POST["tel"]);
$message = trim($_POST["message"]);
$recaptchaSecret = "6LcjwkUUAAAAAENXcZtla40jNuPJGblZkYxLkXvf";
$captcha = '';
if(isset($_POST["captcha"]) && !empty($_POST["captcha"])){
$captcha=$_POST["captcha"];
}
if(!$captcha){
echo 'Prove that you are human';
exit;
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6LcjwkUUAAAAAENXcZtla40jNuPJGblZkYxLkXvf&response=".$captcha."&remoteip=".$_SERVER["REMOTE_ADDR"]);
$obj = json_decode($response);
if($obj->success == true) {
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR empty($tel) OR empty($captcha) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Build the email content.
$email_content = "Имя: $name\n";
$email_content .= "Телефон: $tel\n";
$email_content .= "Email: $email\n";
$email_content .= "Сообщение: $message\n";
// Send the email.
$mail = new PHPMailer();
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'domain.tld'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'info'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
//$mail->setFrom($name, $email);
$mail->setFrom('info#domain.tld', 'DOMAIN.TLD');
$mail->addAddress('info#domain.tld', 'Information'); // Add a recipient
$mail->addReplyTo('info#domain.tld', 'Information');
//Content
$mail->Subject = 'Новое сообщение с сайта DOMAIN.TLD' ;
$mail->Body = $email_content;
$success = $mail->send();
echo "success";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "Something went wrong. Please try again";
}
?>
And not working, giving 403:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
require("PHPMailer.php");
require("Exception.php");
require("SMTP.php");
require('recaptcha-master/src/autoload.php');
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$tel = trim($_POST["tel"]);
$message = trim($_POST["message"]);
$recaptcha = $_POST["g-recaptcha-response"];
$secret = '6LcjwkUUAAAAAENXcZtla40jNuPJGblZkYxLkXvf';
}
//$recaptcha = new \ReCaptcha\ReCaptcha($secret, new \ReCaptcha\RequestMethod\CurlPost());
$recaptcha = new \ReCaptcha\ReCaptcha($secret, new \ReCaptcha\RequestMethod\SocketPost());
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if ($resp->isSuccess()) {
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR empty($tel) OR empty($recaptcha) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Build the email content.
$email_content = "Имя: $name\n";
$email_content .= "Телефон: $tel\n";
$email_content .= "Email: $email\n";
$email_content .= "Сообщение: $message\n";
// Send the email.
$mail = new PHPMailer();
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'domain.tld'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'info'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('info#domain.tld', 'DOMAIN.TLD');
$mail->addAddress('info#domain.tld', 'Information'); // Add a recipient
$mail->addReplyTo('info#domain.tld', 'Information');
//Content
$mail->Subject = 'Новое сообщение с сайта DOMAIN.TLD' ;
$mail->Body = $email_content;
$success = $mail->send();
echo "success";
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "Something went wrong. Please try again";
}
?>
Really thankful for any hints! Thank you in advance.
Finally I found working solution with curl not using standard google recaptcha library, just plain curl. The code needs a lot of cleaning but it's working. Here it is:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
require('PHPMailer.php');
require('Exception.php');
require('SMTP.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = strip_tags(trim($_POST['name']));
$name = str_replace(array('\r','\n'),array(' ',' '),$name);
$email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
$tel = trim($_POST['tel']);
$message = trim($_POST['message']);
$secret = '6LcjwkUUAAAAAENXwZtla40jNuPJGblZkYxLkXvf';
$captcha = '';
if(isset($_POST['captcha']) && !empty($_POST['captcha'])){
$captcha=$_POST['captcha'];
}
if(!$captcha){
echo 'Prove that you are human';
exit;
}
$fields = array(
'secret' => $secret,
'response' => $_POST['captcha'],
'remoteip' => $_SERVER['REMOTE_ADDR']
);
$verifyResponse = curl_init('https://www.google.com/recaptcha/api/siteverify');
curl_setopt($verifyResponse, CURLOPT_RETURNTRANSFER, true);
curl_setopt($verifyResponse, CURLOPT_TIMEOUT, 15);
curl_setopt($verifyResponse, CURLOPT_POSTFIELDS, http_build_query($fields));
$responseData = json_decode(curl_exec($verifyResponse));
curl_close($verifyResponse);
if ($responseData->success) {
if ( empty($name) OR empty($message) OR empty($tel) OR empty($captcha) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo 'Oops! There was a problem with your submission. Please complete the form and try again.';
exit;
}
// Build the email content.
$email_content = 'Имя: $name\n';
$email_content .= 'Телефон: $tel\n';
$email_content .= 'Email: $email\n';
$email_content .= 'Сообщение: $message\n';
// Send the email.
$mail = new PHPMailer();
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'domain.tld'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'info'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('info#domain.tld', 'DOMAIN.TLD');
$mail->addAddress('info#domain.tld', 'Information'); // Add a recipient
$mail->addReplyTo('info#domain.tld', 'Information');
//Content
$mail->Subject = 'Новое сообщение с сайта DOMAIN.TLD' ;
$mail->Body = $email_content;
$success = $mail->send();
echo 'success';
}
} else {
http_response_code(403);
echo 'Something went wrong. Please try again';
}
?>
I am trying to create a simple contact form using PHPMailer and here is what i got so far:
contact.php:
<?php
require 'includes/config.php';
require 'includes/phpmailer/PHPMailerAutoload.php';
function sanitize($text) {
$text = trim($text);
if (get_magic_quotes_gpc()) {
$text = stripslashes($text);
}
$text = strip_tags($text);
return $text;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$entries = array();
$response = array();
// Escape and extract all the post values
foreach ($_POST as $key => $value) {
$entries[$key] = sanitize($value);
}
$name = $entries['cf_name'];
$email = $entries['cf_email'];
$message = $entries['cf_message'];
$subject = 'Contact form';
$replySubject = 'Contact form';
$mailBody = '<b>Email message</b>';
// Check is an AJAX request
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
// Create a new PHPMailer instance
$mail = new PHPMailer;
// Tell PHPMailer to use SMTP
$mail->isSMTP();
// Set the hostname of the mail server
$mail->Host = MAIL_HOST;
// Set the SMTP port number - 587 for authenticated TLS
$mail->Port = MAIL_PORT;
// Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
// Whether to use SMTP authentication
$mail->SMTPAuth = true;
// Username to use for SMTP authentication
$mail->Username = MAIL_USER;
// Password to use for SMTP authentication
$mail->Password = MAIL_PASS;
// Set who the message is to be sent from
$mail->setFrom($email, $name);
// Set an alternative reply-to address
$mail->addReplyTo($email, $name);
// Set who the message is to be sent to
$mail->addAddress(MAIL_ADDR);
// Set the subject line
$mail->Subject = 'Formularz kontaktowy';
// Set email format to HTML
$mail->isHTML(true);
$mail->CharSet = 'UTF-8';
// HTML version
$mail->Body = $mailBody;
// Convert HTML into a basic plain-text alternative body
$mail->AltBody = strip_tags($mailBody);
// send the message
if ($mail->send()) {
$response['result'] = 1;
} else {
$response['result'] = 0;
$response['error'] = $mail->ErrorInfo;
}
echo json_encode($response);
} else {
header('Location: ' . BASE_URL);
exit();
}
} else {
header('Location: ' . BASE_URL);
exit();
}
config.php
<?php
define('BASE_URL', 'http://example.com');
define('MAIL_HOST', 'smtp.gmail.com');
define('MAIL_PORT', 587);
define('MAIL_USER', 'mygmailemail#gmail.com');
define('MAIL_PASS', 'mygmailpassword');
define('MAIL_ADDR', 'example#email.com');
Client-Side:
$('form').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serializeArray();
var t1 = window.performance.now();
$.ajax({
type: 'POST',
url: this.action,
data: formData
})
.done(function(response) {
console.log('DONE', response);
var t2 = window.performance.now();
console.log('time', (t2 - t1) / 1000);
})
.fail(function(response) {
console.log('FAIL', response);
});
});
I am testing this code locally with EasyPHP Server. As you can see above i log time inside ajax done callback and the average time to send an email is 3-5 seconds which i found ridiculously slow. I am not PHP developer so I have no idea why is it so slow. Is it EasyPHP fault or something else I did wrong? Can you please tell how can I improve this code to send out emails faster?
I am having problem with sending mail using phpmailer. I am a beginner programmer. I am trying to make contact form. My code is as follow(submit.php). Please suggest me.. Thanks in advance .
session_start();
require_once 'libs/phpmail/PHPMailerAutoload.php';
$errors = array();
if(isset($_POST['name'], $_POST['phone'],$_POST['mail'],$_POST['message'])){
$fields = array(
'name' => $_POST['name'],
'phone' => $_POST['phone'],
'email' => $_POST['mail'],
'message' => $_POST['message']
);
foreach ($fields as $field => $data) {
if(empty($data)){
$errors[] = 'The '. $field . ' field is required';
}
}
if(empty($errors)){
$m = new PHPMailer;
$m -> isSMTP();
$m -> SMTPAuth = true;
//$m -> SMTPDebug = 2;
$m -> Host = 'smtp.gmail.com';
$m -> Username = 'xxxx#gmail.com';
$m -> Password = 'xxxx';
$m -> SMTPSecure = 'ssl';
$m -> Port = 465;
$m -> isHTML();
$m -> Subject = 'Contact form submitted';
$m -> Body = 'From: ' . $fields['name']. '('. $fields['phone'] . $fields['email']. ')'.'<p>' .$fields['message'] .'</p> ';
$m -> FromName = 'Contact';
// $m ->addReplyTo($fields['email'], $fields['name']);
$m -> addAddress('ssss#gmail.com', 'xxxxxxxx');
if($m->send()){
header('Location: thanks.php');
die();
}else{
$errors[] = 'Sorry could not send email. Please try again';
}
}
}else{
$errors[] = 'some thing went wrong';
}
$_SESSION['error'] = $errors;
$_SESSION['field'] = $fields;
header('Location: form.php');
My setting phpmailer, everything works
function __construct ($to, $subject, $body) {
date_default_timezone_set('Etc/UTC');
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
$mail->CharSet = 'UTF-8';
//Set the hostname of the mail server
$mail->Host = "mail.xxxxxx.com";
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 25;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
$mail->AuthType = 'PLAIN';
//Username to use for SMTP authentication
$mail->Username = "xxxx";
//Password to use for SMTP authentication
$mail->Password = "xxxx";
//Set who the message is to be sent from
$mail->setFrom('erp#xxxxxx.com');
//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);
//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($body);
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
//$mail->addAttachment('images/phpmailer_mini.png');
$this->mail = $mail;
}
function SendMail () {
//send the message, check for errors
if (!$this->mail->send()) {
return "Mailer Error: " . $this->mail->ErrorInfo;
} else {
return true;
}
}
// using
$email = $this->request->getPost('email');
$smtp = new \SmtpClient($email, 'Test', $template);
$result = $smtp->SendMail();
Remove
$m -> Subject = 'Contact form submitted';
And try again.
When I remove the subject it worked.
I am new to php and i want solution for variable pass in mail function
I am using this way to variable pass mail function but getting issue Code:
<?php
require 'PHPMailer/PHPMailerAutoload.php';
function Send_Mail($to,$subject,$body,$cc = "",$bcc = "")
{
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->SMTPDebug = false;
$mail->Username = 'xyz#gmail.com'; // Your Gmail Address
$mail->Password = '123456'; // Your Gmail Password
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->From = 'xyz#gmail.com'; // From Email Address
$mail->FromName = 'gfgg'; // From Name
$mail->addAddress($to);
$mail->addReplyTo('xyz#gmail.com', 'dfg'); // Same as From Email and From Name.
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $body;
if(!$mail->send()) {
return array('status' => false, 'message' => $mail->ErrorInfo);
}
return array('status' => true, 'message' => 'Email Sent Successfully');
}
if (isset($_REQUEST['submit']))
{
$name=$_POST['name'];
$email=$_POST['email'];
$contact=$_POST['contact'];
echo $name, $email, $contact;
$result = Send_Mail('$name','$email','$contact');
}
pls give me soltution
?>
The Send_Mail function requires minimum 3 parameters, which are $to, $subject and $bodyin this order.
So first of all you are calling your parameters within strings
$result = Send_Mail('$name','$email','$contact');
and in the wrong order.
You should probably try this
$result = Send_Mail($email, "Subject", "Message");
You will have to define $subject and $message variables and replace them with "Subject" and "Message"
Try with -
echo "$name, $email, $contact";
$result = Send_Mail($name,$email,$contact);