Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a problem because my file attechment via a php doesn't work. I tried different tutorials. My last try was the code here:
if($isValid === true) {
// Submit Mail
$mail = new SimpleMail();
$mail->setTo(YOUR_EMAIL_ADDRESS, YOUR_COMPANY_NAME)
->setSubject('Neue Mietanfrage')
->setFrom(htmlspecialchars($_POST['email-address']), htmlspecialchars($_POST['first-name'].' '.$_POST['last-name']))
->addGenericHeader('X-Mailer', 'PHP/' . phpversion())
->addGenericHeader('Content-Type', 'text/html; charset="utf-8"')
->setMessage(createMessage($_POST))
->setWrap(100);
$mail->send();
// Submit Client Mail
$mailClient = new SimpleMail();
$mailClient->setTo(htmlspecialchars($_POST['email-address']), htmlspecialchars($_POST['first-name'].' '.$_POST['last-name']))
->setSubject('Ihre Mietanfrage bei '.YOUR_COMPANY_NAME)
->setFrom(YOUR_EMAIL_ADDRESS, YOUR_COMPANY_NAME)
->addGenericHeader('X-Mailer', 'PHP/' . phpversion())
->addGenericHeader('Content-Type', 'text/html; charset="utf-8"')
->setMessage(createClientMessage($_POST))
->setWrap(100);
$mailClient->send();
$result = array(
'result' => 'success',
'msg' => array('Ihre Reservierung wurde erfolgreich übermittelt.')
);
echo json_encode($result);
} else {
$result = array(
'result' => 'error',
'msg' => $isValid
);
echo json_encode($result);
}
//*** Attachment ***//
if($_FILES["fileAttach"]["name"] != "")
{
$strFilesName = $_FILES["fileAttach"]["name"];
$strContent = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));
$strHeader .= "--".$strSid."\n";
$strHeader .= "Content-Type: application/octet-stream; name=\"".$strFilesName."\"\n";
$strHeader .= "Content-Transfer-Encoding: base64\n";
$strHeader .= "Content-Disposition: attachment; filename=\"".$strFilesName."\"\n\n";
$strHeader .= $strContent."\n\n";
}
<input type="file" name="fileAttach" id="fileAttach" hidden>
Why doesnt that worked for me? I just followed the tutorial but nothing helped. Do you have any idea what I have to do? The other informations like the text fields are sending without problems.
I get the informations from that form with javascript. Does that script pay any role why the email doesnt send with the attachment?
$( "#umzug-form" ).submit(function() {
$('#umzug-form-msg').addClass('hidden');
$('#umzug-form-msg').removeClass('alert-success');
$('#umzug-form-msg').removeClass('alert-danger');
$('#umzug-form input[type=submit]').attr('disabled', 'disabled');
$.ajax({
type: "POST",
url: "php/umzug.php",
data: $("#umzug-form").serialize(),
dataType: "json",
success: function(data) {
if('success' == data.result)
{
$('#umzug-form-msg').css('visibility','visible').hide().fadeIn().removeClass('hidden').addClass('alert-success');
$('#umzug-form-msg').html(data.msg[0]);
$('#umzug-form input[type=submit]').removeAttr('disabled');
$('#umzug-form')[0].reset();
}
if('error' == data.result)
{
$('#umzug-form-msg').css('visibility','visible').hide().fadeIn().removeClass('hidden').addClass('alert-danger');
$('#umzug-form-msg').html(data.msg[0]);
$('#umzug-form input[type=submit]').removeAttr('disabled');
}
}
});
return false;
});
You aren't adding the file to the mail object anywhere.
SimpleMail provides the method addAttachment to add attachments to your email.
I'm extending your code with the needed lines:
// Submit Mail
$mail = new SimpleMail();
$mail->setTo(YOUR_EMAIL_ADDRESS, YOUR_COMPANY_NAME)
->setSubject('Neue Mietanfrage')
->setFrom(htmlspecialchars($_POST['email-address']), htmlspecialchars($_POST['first-name'].' '.$_POST['last-name']))
->addGenericHeader('X-Mailer', 'PHP/' . phpversion())
->addGenericHeader('Content-Type', 'text/html; charset="utf-8"')
->setMessage(createMessage($_POST))
->setWrap(100);
// add the following lines to your code
if (isset($_FILES['fileAttach']['tmp_name'])) {
$mail->addAttachment(
$_FILES['fileAttach']['tmp_name'],
$_FILES['fileAttach']['name']
);
}
$mail->send();
SimpleMail will load the contents of the file by itself.
Related
I have an AngularJS app that sends emails using a PHP document.
The email body includes two links to images that are populated with a JS variables.
Most of the emails arrive good and the links work, but in some of them, the links (both or one of them) will come out broken, looking like this:
https://blabla.com/register/uploads/Frankfurt2018-22-03-2018-16-07-52.!
Or like this:
https://blabla.com/register/uploads/KoelnerListe2%21
Or like this:
https://blabla.com/register/upload!
It's weird cause sometimes is both links, sometimes is only one, and most of the times are correct.
The link variable comes from the Angular app and looks like this:
$scope.sendapplication = function(){
$scope.photoor = "https://blabla.com/register/uploads/"+$scope.photoor;
$scope.photosmall = "https://blabla.com/register/uploads/"+$scope.photo;
$scope.exhibitor = {
'img':$scope.photosmall,
'imgoriginal':$scope.photoor,
};
var $promise=$http.post('emailtest.php',$scope.exhibitor);
$promise.then(function (data) {
...
});
};
And in the php file I do this:
$contentType = explode(';', $_SERVER['CONTENT_TYPE']); // Check all available Content-Type
$rawBody = file_get_contents("php://input"); // Read body
$data = array(); // Initialize default data array
if(in_array('application/json', $contentType)) {
$data = json_decode($rawBody); // Then decode it
$photo = $data->img;
$photooriginal = $data->imgoriginal;
} else {
parse_str($data, $data); // If not JSON, just do same as PHP default method
}
header('Content-Type: application/json; charset=UTF-8');
echo json_encode(array( // Return data
'data' => $data
));
$sabine = 'blabla#gmail.com';
$headerss = "From: ".$galleryname."<".$email.">\r\nReturn-path: ".$email."";
$headerss .= "Reply-To: ".$galleryname."<".$email.">";
$headerss .= "MIME-Version: 1.0\r\n";
$headerss .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$recipient = $sabine;
$subjects = "Registration for ".$fairumlaut." - ".$galleryname."";
$bodys .= "<p><strong>Original photo</strong>: Link</p>";
$bodys .= "<p><strong>Web resized photo</strong>: Link</p>";
$bodys .= "<p></p>";
mail($recipient, $subjects, $bodys, $headerss);
What could cause such weird behaviour?
wrap the link in urlencode function. This will solve your issue.
update: or if I read your code I would have seen that the links are coming from JS. Try encodeURI().. ;)
I have been trying recently to use AJAX in a form I posses in order to prevent the page from reloading. I learned AJAX through thenewboston's videos and I've tried to match it to my form.
HTML:
<label for="f_name">Name:</label>
<input type="text" name="f_name" id="f_name" />
<label for="f_email">E-Mail:</label>
<input type="text" name="f_email" id="f_email" />
<label for="f_subj">Subject:</label>
<input type="text" name="f_subj" id="f_subj" /><br />
<div id="status"></div>
<button id="b_send" onClick="process()">Send</button>
JavaScript
function process() {
var name = encodeURIComponent(document.getElementById("f_name").value);
var email = encodeURIComponent(document.getElementById("f_email").value);
var sbj = encodeURIComponent(document.getElementById("f_subj").value);
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
xmlHttp.open("POST", "send.php", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send("name="+name+"&email="+email+"&subj="+sbj);
} else {
setTimeout('process()', 1000);
}
}
function handleServerResponse() {
if (xmlHttp.readyState == 4) { // AJAX is ready!
if (xmlHttp.status == 200) { // 200 = Comms went OK!
var xmlResponse = xmlHttp.responseXML;
var xmlDocumentElement = xmlResponse.documentElement;
var message = xmlDocumentElement.firstChild.data;
document.getElementById("status").innerHTML = '<span style="color:blue">' + message + '</span>';
} else {
alert('Something went wrong!');
}
}
PHP:
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
$name = $_POST['name'];
$email = $_POST['email'];
$sbj = $_POST['subj'];
$src = 'BETA';
$to = "someone#somewhere.com";
$subject = "CONTACT | From: " . $name . " , " . $email . " | '" . $sbj . "' | " . $src . "";
$body = "
<html><body>
<h4>From: ".$name." , ".$email."</h4>
<h4>Subject: ".$sbj."</h4>
<h5>Source: BETA</h5>
</body></html>";
$headers = "From: someone#somewhere.com\r\n";
$headers .= "Reply-To: \r\n";
$headers .= "CC: \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$response = 'Error!';
if (mail($to, $subject, $body, $headers)) {
$response = 'Sent!';
} else {
$response = 'Error 202!';
}
echo '<response>';
echo strip_tags($response);
echo '</response>';
exit(); // I had to use exit() due to my hosting adding up code after every PHP page.
?>
After I click on the button, it shows me the PHP page with the following saying:
This XML file does not appear to have any style information associated
with it. The document tree is shown below.
and the XML code below it:
<response>Sent!</response>
So what now?
The message is a warning. An XML document is a data structure but does not contain any presentation/style information internally. Normally an XML document is used in inter-application communication or as a pure data structure that is then used with additional presentation/style information to display to users.
You are outputing your data in xml format using following lines,
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
If you are trying to get the response from your ajax call, remove xml header and simply echo proper response or use JSON to get your data.
or if you want to display xml file without the warning, you can attach a stylesheet to your xml document like this:
<?xml-stylesheet type="text/css" href="your_stylesheet.css"?>
XML-Stylesheet Reference: http://www.w3.org/TR/xml-stylesheet/
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);
This question already has an answer here:
PHP attachment in email is empty
(1 answer)
Closed 9 years ago.
Im trying to take data from the database and display it in a CSV file which is both downloadable and emailed to someone. I have managed to get the downloadable file working and it displays all of the correct data. It also sends a CSV file to the necessary person but that CSV file is empty and no data is displayed in it.
Here is my code:
$myroot = "../../";
include($myroot . "inc/functions.php");
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=surveys.csv');
$output = fopen('php://output', 'w');
// Create CSV file
fputcsv($output, array('Name', 'Branch', 'Website','Company', 'Question1', 'Question2', 'Question3', 'Question4', 'Question5'));
$mysql_connection = db_connect_enhanced('*****','*****','*****','*****');
$query='SELECT * FROM *****.*****';
$surveys = db_query_into_array_enhanced($mysql_connection, $query);
$count = count($surveys);
$data = array();
for($i=0; $i<=$count; $i++){
$data[] = array($surveys[$i]['FeedbackName'], $surveys[$i]['BranchName'], $surveys[$i]['FeedbackWebsite'], $surveys[$i]['FeedbackCompany'], $surveys[$i]['Question1'], $surveys[$i]['Question2'], $surveys[$i]['Question3'], $surveys[$i]['Question4'], $surveys[$i]['Question5']);
}
foreach( $data as $row )
{
fputcsv($output, $row, ',', '"');
}
fclose($output);
$encoded = chunk_split(base64_encode($output));
// create the email and send it off
$subject = "File you requested from RRWH.com";
$from = "*****#*****.com";
$headers = 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-Type: multipart/mixed;
boundary="----=_NextPart_001_0011_1234ABCD.4321FDAC"' . "\n";
$message = '
This is a multi-part message in MIME format.
------=_NextPart_001_0011_1234ABCD.4321FDAC
Content-Type: text/plain;
charset="us-ascii"
Content-Transfer-Encoding: 7bit
Hello
We have attached for you the PHP script that you requested from http://rrwh.com/scripts.php
as a zip file.
Regards
------=_NextPart_001_0011_1234ABCD.4321FDAC
Content-Type: application/octet-stream; name="';
$message .= "surveys.csv";
$message .= '"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="';
$message .= "surveys.csv";
$message .= '"
';
$message .= $encoded;
$message .= '
------=_NextPart_001_0011_1234ABCD.4321FDAC--
';
mail("*****#*****.com", $subject, $message, $headers, "-f$from");
I've spent a day and a half on this but I cant see the problem. Could someone please point it out to me as to why the attached CSV file is empty?
i'm getting kind of desperate and stressed out :( please someone help me.
base64_encode() expects the parameter to be a string and you give it a (closed) resource.
Try to read the resource into a string, or use file_get_contents or build your string while you write into the resource.
Update:
Try and replace
foreach( $data as $row )
{
fputcsv($output, $row, ',', '"');
}
fclose($output);
$encoded = chunk_split(base64_encode($output));
by
$myoutput = '"Name","Branch","Website","Company","Question1","Question2","Question3","Question4","Question5"';
foreach( $data as $row )
{
$myoutput .= "\"".implode('","',$row)."\"\n";
fputcsv($output, $row, ',', '"');
}
fclose($output);
$encoded = chunk_split(base64_encode($myoutput));
This way, everything you write into your output you also write into a new variable ($myoutput). Since this is a string you can use it with base64_encode().
I know this has been asked before and I have looked at every post I could find that deals with this. I still cannot get the jQuery.post function to correctly receive the error from a php script. Here are both.
PHP:
<?php
##CONFIGURATION
# LIST EMAIL ADDRESS
$toemail = "email here";
# SUBJECT (Subscribe/Remove)
$subject = "Someone has contacted International Designs";
# RESULT PAGE
$location = "../thank-you.php";
## FORM VALUES ##
$myname = $_REQUEST['myname'];
$myemail = $_REQUEST['myemail'];
$mymessage = $_REQUEST['mymessage'];
if ( empty($myname) || empty($myemail) || empty($mymessage) ) {
exit('{"error":"That value was invalid!"}')
} else {
# SENDER
$email = $myname . " <" . $myemail . ">";
# MAIL BODY
$body .= "Name: " . $myname . " \n\n";
$body .= "Email: " . $myemail . " \n\n";
$body .= "Message: " . $mymessage . " \n\n";
# add more fields here if required
## SEND MESSGAE ##
mail( $toemail, $subject, $body, "From: $email" ) or die ("Mail could not be sent.");
}
?>
JS:
if (verify(myname, myemail, mymessage, human, hash, patt)) {
$.post(myform.attr('action'), myform.serialize(), function() {
$('#email-success').fadeIn();
myform[0].reset();
setTimeout("$('#email-success').fadeOut();", 5000);
}, 'json')
.fail(function() {
alert('An error has occurred. Please try again later.')
});
}
I have tried about 5 different methods already, none of which have worked. When I put 'json' as the datatype in the .post function the .fail always fires, no matter what's in the php script. If I leave datatype out, then .fail never fires under any circumstance. I have a feeling the problem is with the php commands and datatype. Any help is appreciated.
Perhaps it's because you don't change the http header code of your response and don't specify your data type response.
You're php code response to front (jQuery) code with a "200 – OK" status in any case, but you expect an error in some case with an 'HTTP/1.0 400 – Bad Request' response Or a 'HTTP/1.0 500 Internal Server Error'.
And, like say Eggplant, you have to specify your response data type as 'Content-Type: application/json'.
So, the final code would be something like this :
<?php
...
header('HTTP/1.0 204 – No Content', true, 204);
header('Content-Type: application/json');
if ( empty($myname) || empty($myemail) || empty($mymessage) ) {
header('HTTP/1.0 400 – Bad Request', true, 400);
exit('{"error":"That value was invalid!"}')
} else {
...
$send = mail( $toemail, $subject, $body, "From: $email" );
if (!$send)
header('HTTP/1.0 500 – Internal Server Error', true, 500);
exit ('{"error":"Mail could not be sent."}');
}
}
return;
?>
For the Warning Cannot modify header information - headers already sent by (output started at /homepages/.../design/contact.php:1) you can examine this answer on the same problem.
Output can be:
Unintentional:
Whitespace before
UTF-8 Byte Order Mark
Previous error messages or notices
Intentional:
print, echo and other functions producing output (like var_dump)
Raw areas before
Update after chat session : it's was a UTF-8 BOM problem
try this
if (verify(myname, myemail, mymessage, human, hash, patt)) {
$.ajax({
type :'POST',
data :$("#myformid").serialize(),
beforeSend:function(){
},
success:function(res){
if(res=='ok'){
setTimeout("$('#email-success').fadeOut();", 5000);
}else{
//read respon from server
alert(res)
}
},
error:function(){
//error handler
}
});
}
and just example
$send = mail(....);//your mail function here
echo ($send) ? "ok" : "Error";
Although, yours is a valid JSON data, I always recommend to use json_encode() function to create JSON string.
exit(json_encode(array("error" => "That value was invalid!")));
Another is make sure you send correct headers to ensure the script knows its a json data. So
header('Content-Type: application/json');
exit(json_encode("error" => "That value was invalid!"));