Sendgrid 202 - email not being sent - php

On submitting a form I receive a status code of 202 (response received, email is queued for delivery), with "Form successfully sent" but the email never gets sent.
I've tried re-creating my API key, and have not found an explanation for this behavior from the API.
Is there a workaround to this scenario?
<?php
require("sendgrid-php/sendgrid-php.php");
// an email address that will be in the From field of the email.
$from = 'Demo contact form <test#example.com >';
// an email address that will receive the email with the output of the form
$to = 'Demo contact form <test#example.com>';
// subject of the email
$name = $_POST['name'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'email' => 'Email', 'phone' => 'Phone', 'subject' => 'Subject', 'message' => 'Message');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
/*
* LET'S DO THE SENDING
*/
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$content = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$content .= "$fields[$key]: $value\n";
}
}
/* All the necessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
*/
// Send email
//mail($to, $subject, $content, implode("\n", $headers));
//recaptcha-response
$recaptcha_secret = "6LfK7ygUAAAAAIYzE6mbqdxbmuroi4gJWqdIpmBu";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true);
if($response["success"] === true){
$from = new SendGrid\Email("Nami19", "namitajamwal19#gmail.com");
// $subject = "Sending with SendGrid is Fun";
// $subject = $_POST['subject'];
$subject= "You have got mail!";
$to = new SendGrid\Email("Example User", "etest549#gmail.com");
$content = new SendGrid\Content("text/html", "
Email : {$email}<br>
Name: {$name}<br>
Subject : {$subject}<br>
Message : {$message}
");
// $content = $_POST["content"];
// $content = $_POST['content'];
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$apiKey = ('SG.4J8IyicKTRqOcu7rOUmJXQ.mLk27ighheFPG4wDF63b5JboXvpGJFZMe');
$sg = new \SendGrid($apiKey);
$sg_response = $sg->client->mail()->send()->post($mail);
echo $sg_response->statusCode();
print_r($sg_response->headers());
echo $sg_response->body();
echo "Form Submit Successfully.";
}else{
echo "You are a robot";
}
// $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
/*
if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
*/
?>

Related

PHP Failure on Form

Apologies, I'm mostly self taught. I'm using the following code live on https://www.poadvisory.com/contact.html and the contact form appears to be working, ReCaptcha as well, but the email never comes. I've spent countless times on the phone with my hosting provider and they claim is a code issue and not a server issue. Surely it's something obvious I don't see. If anyone can help, I'd really appreciate it. I've searched the current questions but don't believe this is a duplicate question.
<?php
require('recaptcha-master/src/autoload.php');
$sendTo = 'Contact Form < my email goes here>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message');
$okMessage = 'Contact form successfully submitted. Thank you, We will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
$recaptchaSecret = 'removed';
error_reporting(E_ALL & ~E_NOTICE);
try {
if (!empty($_POST)) {
if (!isset($_POST['g-recaptcha-response'])) {
throw new \Exception('ReCaptcha is not set.');
}
$recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$response->isSuccess()) {
throw new \Exception('ReCaptcha was not validated.');
}
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
} catch (\Exception $e) {
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
} else {
echo $responseArray['message'];
}

Contact form results appearing in different format

Hi guys I am having an issue where my contact form returns results in a different text format and I was wondering if there is perhaps anything wrong with my header in my contact form php.
I get results such as: цветник на могилу цветник на могилу (Example email where someone filled in the contact form and this was the result when I received the email.
I have tried converting the text and seeing if it is text, for we get spam emails at times
<?php
/*
THIS FILE USES PHPMAILER INSTEAD OF THE PHP MAIL() FUNCTION
*/
require 'PHPMailer-master/PHPMailerAutoload.php';
// an email address that will be in the From field of the email.
$fromEmail = 'eleccon#global.co.za';*/
$fromEmail = $_POST['email'];
$fromName = $_POST['name'];
/**Add Subject in header area of contact form**/
// an email address that will receive the email with the output of the
form
$sendToEmail = 'travelwithus#fellengtours.com';
$oldEmail = 'eleccon#global.co.za';
$sendToName = 'Felleng Tours';
// subject of the email
/*$subject = 'Felleng Tours contact form';*/
$subject = $_POST['subject'];
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'email' => 'Email', 'subject' =>
'Subject', 'message' => 'Message');
// message that will be displayed when everything is OK :)
$okMessage = '<strong>Contact form successfully submitted. Thank you, I
will get back to you soon!</strong>';
// If something goes wrong, we will display this message.
$errorMessage = '<strong>There was an error while submitting the form.
Please try again later</strong>';
/*
* LET'S DO THE SENDING
*/
// if you are not debugging and don't need error reporting, turn this off
by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailTextHtml = "<h1>Felleng Tours Contact Form!</h1><hr>";
$emailTextHtml .= "<table>";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td>
</tr>";
}
}
/* $emailTextHtml .= "</table><hr>";
$emailTextHtml .= "<p>Have a nice day,<br>Kind Regards,<br>Felleng
Tours</p>";*/
$mail = new PHPMailer(true);
$mail->setFrom($fromEmail, $fromName);
$mail->addAddress($sendToEmail, $sendToName); // you can add more
addresses by simply adding another line with $mail->addAddress();
$mail->addAddress($oldEmail, $sendToName); // you can add more addresses
by simply adding another line with $mail->addAddress();
/*$mail->addAddress($fromEmail, $fromName);*/ // you can add more
addresses by simply adding another line with $mail->addAddress();
/* $mail->addReplyTo($_POST['email']);*/
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->msgHTML($emailTextHtml); // this will also create a plain-text
version of the HTML email, very handy
if(!$mail->send()) {
throw new \Exception('I could not send the email.' . $mail-
>ErrorInfo);
}
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
// $responseArray = array('type' => 'danger', 'message' => $errorMessage);
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: text/plain; charset=utf-8');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
?>

How can I get the name, email and subject in this form become the actual values in the message I receive from the server?

How can I configure the variables $from & $subject on top so that the email the server sends me uses those values instead of static text?
<?php
// configure
$from = 'Demo contact form <demo#domain.com>';
$sendTo = 'Demo contact form <demo#domain.com>'; // Add Your Email
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'subject' => 'Subject', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in the email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
// let's do the sending
try
{
$emailText = "You have new message from contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
I want $from to use the Name value and $subject to use the Subject value.
Use the following:
# checks if the 'name' key has been $_POST'ed
$from = isset($_POST['name'])?$_POST['name']:$from;
# checks if the 'subject' key has been $_POST'ed
$subject = isset($_POST['subject'])?$_POST['subject']:$subject;

Navigate to specific url on php form submission

Not really familiar with PHP but I need to use it to submit a form.
However, I want it to navigate to a page after form submission.
Here's my code:
<?php
// configure
$from = 'Demo contact form <demo#domain.com>';
$sendTo = 'Demo contact form <demo#domain.com>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'email' => 'Email'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
try
{
$emailText = "You have new message from contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
Right now, submitting the form takes me to a new page which just shows the $okMessage text
<form id="form" class="topBefore" method="post" role="form" action="contact.php">
<input id="name" name="name" type="text" placeholder="NAME">
<input id="email" name="email" type="text" placeholder="E-MAIL">
<input id="submit" type="submit" value="Send">
Use php header('Location: somepage.php');
if(mail($sendTo, $subject, $emailText, "From: " . $from))
{
header('Location: somepage.php');
}
Note: The php mail() function will return true if the message is accepted for delivery but doesn't guarantee that it will be delivered.
Edit: have a look at my simple email function with try catch statement. Compare with your answer maybe it will help you.
// configure
$from = 'Demo contact form <demo#domain.com>';
$sendTo = 'Demo contact form <demo#domain.com>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'email' => 'Email'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
//post varables from your form
//$name = $_POST['name'];
$name = 'John';
//$email = $_POST['email'];
$email = 'johndoe#blah.com';
//Email header
$header = "MIME-Version: 1.0" . "\r\n";
$header .= "Content-type: text/html;charset=iso-8859-1" . "\r\n";
$header .= "From: $from" . "\r\n";
$header .= "Reply-To: ..." . "\r\n";
$emailText = "You have new message from contact form <br/> ============================ <br/> Name : $name <br/> Email : $email <br/>";
try
{
if (mail('demo#domain.com', $subject, $emailText, $header))
{
header('Location: somepage.php');
}
else
{
throw new Exception($errorMessage);
}
}
catch (Exception $ex)
{
echo 'Message: ' . $ex->getMessage();
}

PHP sends email on page load

<?php
// configure
$from = 'Demo contact form <demo#domain.com>';
$sendTo = '105 Questions <myemail#example.com>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
// let's do the sending
try
{
$emailText = "You have new message from the website\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
This is where I get a little confused some code end with just } and I got errors.
But when I add ?> it works, but also sends an email on page load.
In another post I read they fixed it with isset but when I put it before the "configure comment" an email was still sent on page load.
Basic logic - don't send the message unless you're handling a form submission rather than a page load.
if (isset($_POST['name'])) { //This will not be true on a page load
//Your existing script goes here
}

Categories