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';
}
?>
Related
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I am using mail() function to sent mails when an event happening. But it is not working as I expected. I tried to get the return of the function also. Some one please suggst what may be the issue.
$msg = "Your password has been changed.is'".$data['password']."'";
$to = $data['email'];
$subject = "password changed";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: info#hia.com';
$send = mail($to, $subject, $msg, $headers);
if($send){
echo "successful";
}
else{
echo "error";
}
Problems arising from the php setting. Closing function for security by some service provider. You must send mail with SMTP.
Example several SMTP class on github;
hujuice/smtp - snipworks/php-smtp - PHPMailer/PHPMailer
Example code a PHPMailer according to your code;
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'info#hia.com'; // SMTP username
$mail->Password = 'yourmailpassword'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('info#hia.com', 'Mailer');
$mail->addAddress($data['email']); // Name is optional
$mail->addReplyTo('info#hia.com', 'Information');
$mail->addCC('cc#hia.com');
$mail->addBCC('bcc#hia.com');
$mail->CharSet = 'ISO-8859-1';
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'password changed';
$mail->Body = 'Your password has been changed.is "'.$data['password'].'"';
if(!$mail->send()) {
echo 'error';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'successful';
}
Don't use simple mail(), i prefer for PHPmailer function.
Here is a Example.
First - download phpmailer in your project directory.
second - create send_mail.php in your directory(you can change you name).
send_mail.php file code.
require_once "PHPMailer/PHPMailerAutoload.php";
$mail = new PHPMailer(true);
if (!isset($_POST['send'])) {
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the enquiry form!";
die;
}
$to="abc#xyz.com";
$senderName = "xyz";
//send the mail
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$zcode = $_POST["zcode"];
$email = $_POST["email"];
$phone = $_POST["phone"];
//Enable SMTP debugging.
$mail->SMTPDebug = 0;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "smtp.gmail.com";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "abc#xyz.com";
$mail->Password = "########";
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "ssl";
//Set TCP port to connect to
$mail->Port = 465;
$mail->From = $to;
$mail->FromName = $senderName;
$mail->addAddress($to, $senderName);
$mail->addReplyTo($email, $name);
$mail->isHTML(true);
$mail->Subject = "bfuiebfiaif";
$mail->Body = "as per your needs";
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
die;
}
header('Location: index.php');
die;
I have done a contact form and obviously I would like to receive a confirmation email when a user fill out this form on my website.
I'm using PHPMailer. When I test the code on my computer as localhost, everything works fine and confirmation message is received properly.
Here you are the PHP script:
<?php
$Name= $_POST['Name'];
$Email = $_POST['Email'];
$Message = $_POST['Message'];
if ($Name=='' || $Email=='' || $Message==''){
echo "<script>alert('Please fill out mandatory fields');location.href ='javascript:history.back()';</script>";
}else{
require("archivosformulario/class.phpmailer.php");
$mail = new PHPMailer();
$mail->From = $Email;
$mail->FromName = $Name;
$mail->AddAddress("myemail#gmail.com");
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = "Contact Form";
$mail->Body = "Name: $name \n<br />".
"Email: $Email \n<br />".
"Message: $Message\n<br />";
// SMTP Server
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Port = 465;
$mail->SMTPSecure = "ssl";
$mail->Username = "myemail#gmail.com";
$mail->Password = "mypassword";
if ($mail->Send())
echo "<script>alert('We have received your message. We will contact you shortly.');location.href ='javascript:history.back()';</script>";
else
echo "<script>alert('Error');location.href ='javascript:history.back()';</script>";
}
?>
The problem is when I upload this PHP script on a web hosting (i.e 123-reg.co.uk), it doesn´t work.
Error message:
SMTP Error: Data not accepted
Here you are the PHP script:
<?php
$Name= $_POST['Name'];
$Email = $_POST['Email'];
$Message = $_POST['Message'];
if ($Name=='' || $Email=='' || $Message==''){
echo "<script>alert('Please fill out mandatory fields');location.href ='javascript:history.back()';</script>";
}else{
require("archivosformulario/class.phpmailer.php");
$mail = new PHPMailer();
$mail->From = $Email;
$mail->FromName = $Name;
$mail->AddAddress("email#mydomainat123-reg.com");
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = "Contact Form";
$mail->Body = "Name: $name \n<br />".
"Email: $Email \n<br />".
"Message: $Message\n<br />";
// SMTP Server
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->Host = "smtp.123-reg.co.uk";
$mail->SMTPAuth = true;
$mail->Port = 25;
$mail->Username = "email#mydomainat123-reg.com";
$mail->Password = "password";
if ($mail->Send())
echo "<script>alert('We have received your message. We will contact you shortly.');location.href ='javascript:history.back()';</script>";
else
echo "<script>alert('Error');location.href ='javascript:history.back()';</script>";
}
?>
I have tried uploading and executing this PHP script from another free web hosting but it was to not avail.
I'm kind of new in PHP, especially in dealing with mail functions.
What can be the reason? Any additional help would be appreciated.
Thanks in advance for your help.
Your server doesn't allow different sender and username you should config: $mail->From like $mail->Username
Moreover...
Most times I've seen this message the email gets successfully sent anyway, but not always. To debug, set:
$mail->SMTPDebug = true;
You can either echo the debug messages or log them using error_log():
// 'echo' or 'error_log'
$mail->Debugoutput = 'echo';
A likely candidate especially on a heavily loaded server are the SMTP timeouts:
// default is 10
$mail->Timeout = 60;
class.smtp.php also has a Timelimit property used for reads from the server!
Hope this information helps! :)
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 have a phpmailer form that is sending email perfectly fine however a I would like to send 2 emails per form submit. The first email should be the form field values to myself. Thsi works as expected. I am having toruble finding any documentation that would allow me to send a second email to the person who submitted the form to say thanks for contacting us we will be in touch shortly. I basically would like to send a second email to the value you $_POST['email'] with "Thank You" as the contents.
The form code (without any thank you email):
require 'library/extensions/PHPMailerAutoload.php';
$mail = new PHPMailer;
$strMessage = "";
//Only action if the form has been submitted
if(isset($_POST['submit-contact-new'])) {
//Validate the fields again, because not everyone has Javascript, including bots
if (isset($_POST['name']) && $_POST['name'] !== "" &&
isset($_POST['surname']) && $_POST['surname'] !== "" &&
isset($_POST['email']) && $_POST['email'] !== "" &&
isset($_POST['phone']) && $_POST['phone'] !== "" &&
isset($_POST['comment']) && $_POST['comment'] !== "") {
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'mail.domain.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'noreply#domain.com'; // SMTP username
$mail->Password = 'passwd'; // SMTP password
$mail->From = 'noreply#domain.com';
$mail->FromName = 'Domain';
$mail->addAddress('staffmember#domain.com', 'First Last'); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Domain Form Enquiry';
$mail->Body = '
<html>
<body>
<h1>Domain Website Enquiry</h1>
<p>Information on form was:</p>
<p><strong>Name</strong>: '.$_POST['name'].'</p>
<p><strong>Surname</strong>: '.$_POST['surname'].'</p>
<p><strong>Email</strong>: '.$_POST['email'].'</p>
<p><strong>Phone</strong>: '.$_POST['phone'].'</p>
<p><strong>Enquiry</strong>: '.$_POST['comment'].'</p>
</body>
</html>
';
if(!$mail->send()) {
//Finally redirect
header('Location: '.$_SERVER['REQUEST_URI']. '?message='.$strMessage) ;
} else {
//Finally redirect
header('Location: http://domain.com/thank-you?location='.$strLocation) ;
}
} else {
//Something is wrong, so work out what
if (!isset($_POST['name']) || $_POST['name'] === "") $strMessage .= "<li>Name must be entered</li>";
if (!isset($_POST['surname']) || $_POST['surname'] === "") $strMessage .= "<li>Surname must be entered</li>";
if (isset($_POST['surname']) && isset($_POST['surname']) && $_POST['name'] === $_POST['surname']) $strMessage .= "<li>Name and Surname must be different</li>";
if (!isset($_POST['phone']) || $_POST['phone'] === "") $strMessage .= "<li>Phone Number must be entered</li>";
if (!isset($_POST['email']) || $_POST['email'] === "") $strMessage .= "<li>Email must be entered</li>";
if (!isset($_POST['comment']) || $_POST['comment'] === "") $strMessage .= "<li>An enquiry must be entered</li>";
if ($strMessage !== "") $strMessage = "<ul>" . $strMessage . "</ul>";
//Finally redirect
header('Location: '.$_SERVER['REQUEST_URI']. '?message='.$strMessage) ;
exit();
}
}
?>
To resolve this issue I simply put another instance within this form action and ran phpmailer twice. This enabled me to set seperate body contents and reciepts using the same post content.
<?php
require 'library/extensions/PHPMailerAutoload.php';
$mail = new PHPMailer;
$strMessage = "";
//Only action if the form has been submitted
if(isset($_POST['submit-contact-new'])) {
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'mail.domain.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'noreply#domain.com'; // SMTP username
$mail->Password = 'passwd'; // SMTP password
$mail->From = 'noreply#domain.com';
$mail->FromName = 'Domain';
$mail->addAddress('staff#domain.com', 'Staff Name'); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Domain Form Enquiry';
$mail->Body = '
<html>
<body>
<h1>Domain Website Enquiry</h1>
<p>Information on form was:</p>
<p><strong>Name</strong>: '.$_POST['name'].'</p>
<p><strong>Surname</strong>: '.$_POST['surname'].'</p>
<p><strong>Email</strong>: '.$_POST['email'].'</p>
<p><strong>Phone</strong>: '.$_POST['phone'].'</p>
<p><strong>Enquiry</strong>: '.$_POST['comment'].'</p>
</body>
</html>
';
if(!$mail->send()) {
//Finally redirect
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
//Finally redirect
header('Location: http://domain.com/thank-you?location='.$strLocation) ;
}
}
$mail = new PHPMailer;
$strMessage = "";
//Only action if the form has been submitted
if(isset($_POST['submit-contact-new'])) {
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'mail.domain.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'noreply#rdomain.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->From = 'noreply#domain.com';
$mail->FromName = 'Domain';
$mail->addAddress(''.$_POST['email'].''); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Thank you for contacting Domain';
$mail->Body = 'Thanks for getting in touch. Your message has been received and will be processed as soon as possible.';
if(!$mail->send()) {
//Finally redirect
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
//Finally redirect
header('Location: http://domain.com/thank-you?location='.$strLocation) ;
}
}
?>
I have a form on my website where people can join events. The code behind it works in this way:
All info is saved in a database. This part works fine.
The second part of the code send out an email to me and to the user with the info he entered (same info as saved in the database)
The issue is that these emails are sent unauthenticated through a default email on the hosting account. I had to modify the script to force SMTP authentication with a valid email under my hosting account to fix the error. Right now the script sends out the email but it ends in spamfilter with all ISPs so the user never receive the email.
I have no idea of how to do, or create the codes so the script use SMTP authentication. Below is the codes I have so fare. Can someone help me?
<?
// SEND OUT EMAIL PART
// COPY SEND TO MY SELF
$to = "my#email.com";
$from = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$headers = "From: $from";
$subject = "Thanks!";
$fields = array();
$fields{"name"} = "Name";
$fields{"address"} = "Address";
$fields{"phone"} = "Phone";
$fields{"email"} = "E-mail addesse";
$body = "INFO:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }
// SEND TO THE USER
$headers2 = "From: my#email.com";
$subject2 = "THANKS!";
$fields2 = array();
$from = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$headers = "From: $from";
$subject = "Thanks!";
$body2 = "
TEXT TO EMAIL RECEIVER
\n\n"; foreach ($fields2 as $a => $b){ $body2 .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }
// ERROR MESSAGES
if($from == '') {print "MISSING EMAIL ADDRESS.";}
else {
if($name == '') {print "MISSING NAME";}
else {
$send = mail($to, $subject, $body, $headers);
$send2 = mail($from, $subject2, $body2, $headers2);
if($send)
{header( "Location: http://mysite/send.php" );}
else
{print "MISSING EMAIL ADDRESS ALL FILDS MUST BE FILLED!"; }
}
}
?>
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
This is one way to do it. You need to include PHPMailer
#somewhere in code before you call function
include($path_to_PHPMailer."class.smtp.php");
function sendEmail($email,$name,$title,$content,$who=false,$att=array('')){
//VARIABLE $email is email of sender
//VARIABLE $name is name of sender
//VARIABLE $title is title of email
//VARIABLE $content is content of email
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
// DOUBLE $mail->Host = "your email_server"; // SMTP server
$mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "your email_server"; // sets the SMTP server
$mail->Port = server port; // set the SMTP port for the GMAIL server
$mail->Username = "your username"; // SMTP account username
$mail->Password = "your password"; // SMTP account password
if($who){
$mail->SetFrom($email, $name);
$mail->AddReplyTo($email,$name);
$address = "set your email";//EMAIL OF RECIPENT
} else{
$mail->SetFrom("set your email", "your name (or service name)");
$mail->AddReplyTo("set your email","your name (or service name)");
$address = $email;
}
$content=str_replace("\n", "<br>", $content);
$mail->Subject = $title;
$mail->MsgHTML($content);
$mail->AddAddress($address, $name);
$mail->CharSet='utf-8';
if($att[0]!=''){
foreach ($att as $at){
$mail->AddAttachment($at);
}
}
if(!$mail->Send()) {
return false; //$mail->ErrorInfo;
} else {
return true;
}
}