php sendmail form fails, worked for years - php

I have a php contact form which has been working reliably for several years up until Jan 2022. It uses a Google reCaptcha. Apparently it fails at the mailcheck part which is near the end and prints out the "MAIL Sending Failed" message
<?php
//dont need these
error_reporting(E_ALL);
ini_set('display_errors', 1);
// check form is submitted
if ( isset($_POST['form_submit']) ) {
// get values
$error = ''; //error variable
$visitor_name = $_POST['name'];
$visitor_email = $_POST['email'];
$visitor_message = $_POST['message'];
$captcha = $_POST['g-recaptcha-response'];
//required values
if ( empty($visitor_name) || empty($visitor_email) ) {
$error = "<h3>Name and Email are required. END.</h3>";
}
//required captcha
if ( empty($captcha) ) {
$error = "<h3>Please check the the captcha form. END.</h3>";
}
// if no errors
if( empty($error) ){
$secretKey = " *** hidden *** ";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' .
urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response, true);
// should return JSON with success as true
if ($responseKeys["success"]) {
echo '<h3>Captcha Success. Writing Mail...</h3>';
// write mail
$to = " *** my user email ***.com";
$email_subject = "C&H form v2c inquiry";
// To send HTML mail, the Content-type header must be set
// If the From header is not set, then Luxsci servers reject
// $headers = "";
$headers = "From: *** my email ***.com \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
$headers .= "MIME-Version: 1.0 \r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1 \r\n";
$headers .= "X-Mailer: PHP/".phpversion();
$email_body = "message from " . $visitor_name . "<br>" .
"sender's email: " . $visitor_email . "<br>" .
"here is the message: " . $visitor_message;
// compose headers
//Send the mail
$mail_check = mail($to, $email_subject, $email_body, $headers);
if ($mail_check) {
echo "<h5>Mail sending successful. Redirecting... </h5>";
echo '<script> window.location.href = "thank_you_CG.html"; </script>';
} else {
echo "<h5>MAIL sending failed.</h5><br<br>
<h3> This is the failure message it sends out HERE </h3>";
}
} else { // if response not success
echo '<h3>reCaptcha verification failed!</h3>';
echo "Response from reCaptcha: <br>";
print_r($responseKeys);
}
} else { //if errors
echo $error;
exit;
}
}
I can also add the html but there seems to be no problem with that. As mentioned this php form was working fine for years then stopped. I've heard that the Google recaptcha uses a smaller string now?

Related

PHP Send Mails Problems

i'm using a normal php script for recive mail from my website directly to my personal mail. When i try to test and send from contact form a mail to me, output always said: "Something went wrong, please try again" like if there's no validation. It's my first time that i try to incorporate a php script so probably i'm missing something very oblivious.
Here's the code:
<?php
$siteOwnersEmail = 'Myemail#gmail.com';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
PHP mail function send email without SMTP authentication. It would be more accurate to send e-mail with SMTP authentication. I can suggest you to check the link below.
https://github.com/PHPMailer/PHPMailer

How to add redirect when form is submitted [duplicate]

This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 12 months ago.
I have been trying to add form submit to my web form, so that it submits data to my email using POST.
So far this is what I have and it works perfectly:
<?php
if(isset($_POST['submit'])){
$user = $_POST['user'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$to = "your-webmail here";
$subject = "Applied Data";
$txt = "Name-'.$user.',<br>Phone -'.$phone.',<br>Email-'.$email.'";
$headers = "From: your#gmail.com" . "\r\n" .
$headers .= 'Cc: your#gmail.com' . "\r\n";
$ab=(mail($to,$subject,$txt,$headers));
if($ab)
{
echo"<script>alert('SignUp successfully.')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else
{
echo"Failed";
}
}
?>
Is there a way to add a redirect to this code, so it redirects after form is submitted?
You have two options (probably more...)
Refactor your code to use AJAX to process the results of the form;
Don't display the headers until you know whether the form has been submitted / processed correctly. A redirect won't work if headers have already been sent.
As you've provided a non-AJAX problem:
<?php
if(isset($_POST['submit'])){
$user = $_POST['user'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$pageHeaders = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"; // etc.
$to = "your-webmail here";
$subject = "Applied Data";
$txt = "Name-'.$user.',<br>Phone -'.$phone.',<br>Email-'.$email.'";
$headers = "From: your#gmail.com" . "\r\n" .
$headers .= 'Cc: your#gmail.com' . "\r\n";
$ab=(mail($to,$subject,$txt,$headers));
if($ab)
{
header("Location: index.php");
die();
}
else
echo $pageHeaders; // You will need to create page headers
echo"Failed";
}
}
?>
This solution doesn't allow for an alert or message to indicate successful save. This could be achieved by redirecting to an interstitial page which can redirect after a timer. See here for an example:
use $_SESSION or $_COOKIE or a flag in your DB/in a temporary file to read & write.
for example:
if (isset($_SESSION['mail_sent']) && $_SESSION['mail_sent'] === true) {
redirect_to($target_url);
exit;
}
if(isset($_POST['submit'])) {
...
if (sending was successful) {
$_SESSION['mail_sent'] === true
}
else {
$_SESSION['mail_sent'] === false
}
}

How to Send emails to multiple recipients in PHP [duplicate]

This question already has answers here:
PHP mail: Multiple recipients?
(5 answers)
Closed 1 year ago.
I need to send my forms to multiple recipients, but I can't figure it out which line I need to edit. Please see below. I appreciate your help.
I already tried adding more values to the emailto, but I can't get it to work.
I need to send my forms to multiple recipients, but I can't figure it out which line I need to edit. Please see below. I appreciate your help.
I already tried adding more values to the emailto, but I can't get it to work.
Hello there,
I need to send my forms to multiple recipients, but I can't figure it out which line I need to edit. Please see below. I appreciate your help.
<?php
// Configure your Subject Prefix and Recipient here
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$subjectPrefix = $_POST['subject'];
$privacyPolicy = $_POST['privacy-policy'];
$emailTo = stripslashes(trim($_POST['email-to']));
$name = stripslashes(trim($_POST['name']));
$email = stripslashes(trim($_POST['email']));
$phone = stripslashes(trim($_POST['phone']));
$message = stripslashes(trim($_POST['message']));
$spam = $_POST['textfield'];
$confirmMsg = $_POST['confirm'];
$captcha = $_POST['captcha'];
if (empty($name)) {
$errors['name'] = 'Please fill in all required fields.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Please fill in all required fields.';
}
if (empty($message)) {
$errors['message'] = 'Please fill in all required fields.';
}
if (empty($captcha)) {
$errors['captcha'] = 'TEST CAPTCHA';
}
if (empty($privacyPolicy)) {
$errors['privacy_policy'] = 'Please fill in all required fields.';
}
// if there are any errors in our errors array, return a success boolean or false
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$subject = "Message from $subjectPrefix";
$body = '
<strong>Name: </strong>'.$name.'<br />
<strong>Email: </strong>'.$email.'<br />
<strong>Phone: </strong>'.$phone.'<br />
<strong>Message: </strong>'.nl2br($message).'<br />
';
$headers = "MIME-Version: 1.1" . PHP_EOL;
$headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
$headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
$headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '#' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
$headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . " <$email> " . PHP_EOL;
$headers .= "Return-Path: $emailTo" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
$headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;
if (empty($spam)) {
mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
}
$data['success'] = true;
$data['confirmation'] = $confirmMsg;
}
// return all our data to an AJAX call
echo json_encode($data);
}
You can separate receivers by comma like
$to = "somebody#example.com, somebodyelse#example.com";
As indicated in the mail() documentation you can use this:
$emailTo = $mail1 . ', ' . $mail2;

Contact form php script sending spam to Gmail

I created a php script (for a contact form) to send emails to my Gmail account.
If I use the sender email in the header ($headers = "From: " . $email;), Gmail reports the received message as spam.
If I don't use the email in the header (e.g. the sender name $headers = "From: " . $name;) the message is not reported as spam.
Do you have any suggestion to let me use the email in the header?
Thanks!
<?php
/* Check if the url field is empty (antispam) */
if ($_POST['leaveblank'] != '' or $_POST['dontchange'] != 'http://') {
$name = $_POST['name'];
$faillink = "xxx.php";
header("Location: $faillink");
} else {
$name = $_POST['name'];
$email = $_POST['email'];
$subject_prefix = "[ContactForm]: ";
$subject = $subject_prefix . $_POST['subject'];
$message = $_POST['message'];
$to = "myemail#gmail.com";
$body = "From: " . $name . "\n";
$body .= "Email: " . $email . "\n";
$body .= "Message: " . $message . "\n";
$headers = "From: " . $email;
$oklink = "yyy.php";
$faillink = "xxx.php";
if ( preg_match( "/[\r\n]/", $name ) || preg_match( "/[\r\n]/", $email ) ) {
header("Location: $faillink");
}
$retmail = mail($to, $subject, $body, $headers);
if ($retmail) {
header("Location: $oklink");
} else {
header("Location: $faillink");
}
}
?>
I solved the issue as Iain suggested so I replaced the mail headers as follows:
$headers = "From: " . "noreplay#mydomain.com" . "\r\n";
$headres .= "Reply-To: " . $email . "\r\n";

PHP Send-Mail form to multiple email addresses

I'm very new to PHP and am using a basic template 'send-mail' form on a contact page.
It's been requested that I send the email out to multiple email addresses when the "Submit" button is clicked. I've searched around & haven't quite found what I needed. What code do I need to add into the form below in order to send this out to multiple email addresses?
<?php
$mail_to = 'daniel30293#gmail.com'; // specify your email here
// Assigning data from the $_POST array to variables
$name = $_POST['sender_name'];
$mail_from = $_POST['sender_email'];
$phone = $_POST['sender_phone'];
$web = $_POST['sender_web'];
$company = $_POST['sender_company'];
$addy = $_POST['sender_addy'];
$message = $_POST['sender_message'];
// Construct email subject
$subject = 'Web Prayer Request from ' . $name;
// Construct email body
$body_message = 'From: ' . $name . "\r\n";
$body_message .= 'E-mail: ' . $mail_from . "\r\n";
$body_message .= 'Phone: ' . $phone . "\r\n";
$body_message .= 'Prayer Request: ' . $message;
// Construct email headers
$headers = 'From: ' . $name . "\r\n";
$headers .= 'Reply-To: ' . $mail_from . "\r\n";
$mail_sent = mail($mail_to, $subject, $body_message, $headers);
if ($mail_sent == true){ ?>
<script language="javascript" type="text/javascript">
alert('Your prayer request has been submitted - thank you.');
window.location = 'prayer-request.php';
</script>
<?php } else { ?>
<script language="javascript" type="text/javascript">
alert('Message not sent. Please, notify the site administrator admin#bondofperfection.com');
window.location = 'prayer-request.php';
</script>
<?php
}
?>
Your help is greatly appreciated.
You implode an array of recipients:
$recipients = array('jack#gmail.com', 'jill#gmail.com');
mail(implode(',', $recipients), $submit, $message, $headers);
See the PHP: Mail function reference - http://php.net/manual/en/function.mail.php
Receiver, or receivers of the mail.
The formatting of this string must comply with ยป RFC 2822. Some examples are:
user#example.com
user#example.com, anotheruser#example.com
User <user#example.com>
User <user#example.com>, Another User <anotheruser#example.com>
Just add multiple recipients comma seperated in your $mail_to variable like so:
$mail_to = 'nobody#example.com,anotheruser#example.com,yetanotheruser#example.com';
See
mail() function in PHP
Here is a simple example:
<?php
// Has the form been submitted?
// formSubmit: <input type="submit" name="formSubmit">
if (isset($_POST['formSubmit'])) {
// Set some variables
$required_fields = array('name', 'email');
$errors = array();
$success_message = "Congrats! Your message has been sent successfully!";
$sendmail_error_message = "Oops! Something has gone wrong, please try later.";
// Cool the form has been submitted! Let's loop through the required fields and check
// if they meet our condition(s)
foreach ($required_fields as $fieldName) {
// If the current field in the loop is NOT part of the form submission -OR-
// if the current field in the loop is empty, then...
if (!isset($_POST[$fieldName]) || empty($_POST[$fieldName])) {
// add a reference to the errors array, indicating that these conditions have failed
$errors[$fieldName] = "The {$fieldName} is required!";
}
}
// Proceed if there aren't any errors
if (empty($errors)) {
$name = htmlspecialchars(trim($_POST['name']), ENT_QUOTES, 'UTF-8' );
$email = htmlspecialchars(trim($_POST['email']), ENT_QUOTES, 'UTF-8' );
// Email Sender Settings
$to_emails = "anonymous1#example.com, anonymous2#example.com";
$subject = 'Web Prayer Request from ' . $name;
$message = "From: {$name}";
$message .= "Email: {$email}";
$headers = "From: {$name}\r\n";
$headers .= "Reply-To: {$email}\r\n";
$headers .= 'X-Mailer: PHP/' . phpversion();
if (mail($to_emails, $subject, $message, $headers)) {
echo $success_message;
} else {
echo $sendmail_error_message;
}
} else {
foreach($errors as $invalid_field_msg) {
echo "<p>{$invalid_field_msg}</p>";
}
}
}

Categories