I can successfully send emails with App Engine Mail API, but i cannot find the problem for why the attachment do not get attached in email. My code looks like this:
// Pull in the raw file data of the image file to attach it to the message.
$image_data = fopen('gs://pro-sitemaps-api/file.csv');
try {
$message = new Message();
$message->setSender('myemail#****.com');
$message->addTo('myemail#****.com');
$message->setSubject('Subject Google App Engine Test');
$message->setTextBody('Test body');
$message->addAttachment('file.csv', $image_data);
$message->send();
echo 'Mail Sent';
} catch (InvalidArgumentException $e) {
echo 'There was an error'.$e;
}
My file is hosted in Google Storage (bucket). The filetype of storage file is .csv
Can anyone tell me what i am doing wrong?
Edit:
Adding "mode":"r" gives me this error:
$image_data = fopen('gs://pro-sitemaps-api/file.csv', 'r');
Output:
error: {
code: "500",
message: "An error occurred parsing (locally or remotely) the arguments to mail.Send().",
status: "UNKNOWN",
details: [ ]
}
}
Edit:
This works but this only sends the top line (header). not all lines. Tried adding this inside a array and send the array as attachment but then i get same error.:
$fpmail = fopen('gs://pro-sitemaps-api/file.csv', 'r');
//$attach = fread($fpmail);
$attach = fgets($fpmail);
print_r($attach);
try {
$message = new Message();
$message->setSender('asim#redperformance.no');
$message->addTo('asim#redperformance.no');
$message->setSubject('Test');
$message->setTextBody('Test nyeste');
$message->addAttachment('file.csv', $attach);
$message->send();
echo 'Mail Sent';
} catch (InvalidArgumentException $e) {
echo $e;
}
fclose($fpmail);
I don't ever code in PHP, but it looks like you are not actually reading the contents of the file.
In most programming languages, a call like fopen is just the first step of getting the contents of the file, but doesn't actually get the contents. You'll probably need something like this:
$f = fopen('gs://pro-sitemaps-api/file.csv', 'r');
$image_data = $f.read();
but you'll need to figure out how to read data from a file in PHP.
Related
I have an Openhab system on a PI and a REST API and I want to display information on a TV-Screen.
I have tried to do it with a curl and it worked. So now I want to do the same with Guzzle.
First I only installed composer and guzzle in the Project directory on my PC, Then I also installed them on the PI. Neither approach worked as I got a 500 error on both attempts.
function getCurrentTemp() {
echo "test1";
$client = new GuzzleHttp\Client([
'base_uri'=>'http://fernseher/'
]);
echo "test2";
$return = $client->request('GET','http://openhab.clubdrei.com/rest/items/ThermostateTemp/state', ['auth' => ['User','Password']]);
echo $return;
}
I think the creating Client break up the script
I need your help,
Thank you
500 basically means that there is a server error. Please attach the cURL command that is successful (as you mentioned in the question's title).
I also modified your code a bit, to be sure that you are are working with the body content of the response (->getBody()->getContents() part):
function getCurrentTemp()
{
// You don't need 'base_uri' here, because you use absolute URL below
$client = new GuzzleHttp\Client();
$response = $client->request(
'GET',
'http://openhab.clubdrei.com/rest/items/ThermostateTemp/state',
['auth' => ['User','Password']]
);
return $response->getBody()->getContents();
}
I have the following intent for an Alexa Skill and I need to read a .txt file from an external URL into a variable for Alexa to say it. This is what I have so far...
'PlayVoice': function() {
var url = "https://example.com/myfile.txt";
var output = 'Okay, here is the text file' + url;
this.response.speak(output);
this.emit(':responseReady');
},
Obviously, the only thing it does now is to read the actual URL.
I have tried using fs.readFile but I just get an error in the Alexa Skill. This is the code I tried:
'PlayVoice': function() {
var content;
fs.readFile('https://example.com/myfile.txt', function read(err, data) {
content = data;
this.response.speak(content);
}
this.emit(':responseReady');
},
Any help on how to simply read a text file into a variable I can get Alexa to speak via this.response.speak?
You can use request package.
something like this should help.
var request = require('request');
request('url/of/the/file', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // contents of your file.
});
source : https://www.npmjs.com/package/request#super-simple-to-use
Also you'll need to add the package request to your skill's lambda.
To do that install the request package in the folder where your code is (lambda_function.js and all other files). Then create a zip of all the files (not the folder in which your files are) and upload it to your aws lambda.
I'm trying to create a json file on a Apple TV device to save some data but createFile(...) always fails, returning false. I've tried with absolutePath, relativePath and path to no success. The jsonData variable is created just fine in my implementation and it works on the Simulator:
self.fileName = "MyFileTest"
self.directory = .documentDirectory
let documentsDirectory = fileManager.urls(for: self.directory, in: .userDomainMask)[0]
self.fullyQualifiedPath = documentsDirectory.appendingPathComponent(self.fileName).appendingPathExtension("json").path
do {
let jsonData = try convertObjectToData(data: dataForJson)
if !fileManager.createFile(atPath: fullyQualifiedPath, contents: jsonData as Data, attributes: nil) {
print("File Manager failed at createFile")
throw FileErrors.FileNotSaved
}
} catch {
print("Unable to create json file \(error.localizedDescription)")
throw FileErrors.FileNotSaved
}
Here createFile fails and returns false and the following is printed out:
File Manager failed at createFile Unable to create json file The
operation couldn’t be completed.
(TestAppTVOS.FileSaveHelper.(FileErrors in
_70D0A1275AC2AFFFA4ED048E3A809030) error 1.)
The fullyQualifiedPath variable value is:
/var/mobile/Containers/Data/Application/00DCB709-5EC6-40FC-BB21-D797EB4FE2F5/Documents/MyFileTest.json
Not sure what to make out of that error message "The operation couldn’t be completed" and "error 1"? Any ideas how to get this working properly for Swift 3?
After spending a bit too much time on this it seems it was related to which folder I was creating the file in.
As I am in sandbox mode/debugging I could not write to the Documents folder so instead had to switch to the Cache folder.
E.g
self.directory = .cachesDirectory
Works now.
I'm trying to play mp3 files from server-side to client-side. Where the client access the server passing some ID and the server return the file.
Right now, how this is working?
Well, using Laravel (server-side) and AngularJS (client-side) on distinct urls, i'm able to play the song.
But, if I get the request response I'm able to download the song.
So, what would be the good way to work so that information wouldn't be visible to the user?
I would write some sort of file proxy.
You have to move your files out of the publicly accessible area. F.a one level above the page root. So it is not possible to get the data directly.
Then you need a server side script, that gets the data and returns it with the headers you need.
Here is an example (plain PHP):
/**
* #param string $file_name
* #param string $mime
* #param bool $download
*/
public function fileProxyAction($file_name, $mime, $download = false) {
if(basename($file_name) != $file_name) return 'Filename not valid!';
$path = '... your path goes here';
$file = $path.$file_name;
if (!(file_exists($file) && is_readable($file))) return 'The file "'.$file_name.'" could not be found!';
ob_clean();
if($download === false) {
header('Content-type: '.$mime);
header('Content-length: '.filesize($file));
$open = # fopen($file, 'rb');
if ($open) {
fpassthru($open);
exit;
}
} else {
// download
$path_parts = pathinfo($file);
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
header("Content-type: application/octet-stream");
header("Content-length: " . filesize($file));
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
header("Cache-control: private"); // open files directly
readfile($file);
die;
}
}
Laravel has an excellent Built-In-Filesystem. Check it out. I'm sure you can optimize my method with it.
EDIT
If you need to check a token or something, you shouldn't call the fileProxyAction directly by the router. Instead let your router call a Method which checks the token or what ever you're using ;)
Example (pseudo code):
Route::get('/mp3/{id}/{token}', function($id, $token) {
if($token !== Session::get('token')) return App::abort(401);
$name = Mp3::findOrFail($id)->name;
$mime = Mp3::findOrFail($id)->mime;
return $this->fileProxyAction($name, $mime);
});
I am trying to upload multiple files to Google drive using the PHP SDK. For this I am calling the function below iteratively passing the required parameters:
function insertFile($driveService, $title, $description, $parentId, $fileUrl) {
global $header;
$file = new Google_DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$mimeType= "application/vnd.google-apps.folder";
if ($fileUrl != null) {
$fileUrl = replaceSpaceWithHtmlCode($fileUrl);
$header = getUrlHeader($fileUrl);
$mimeType = $header['content-type'];
}
$file->setMimeType($mimeType);
$parent = new Google_ParentReference();
// Set the parent folder.
if ($parentId != null) {
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = null;
if ($fileUrl != null) {
if (hasErrors($driveService, $fileUrl) == True) {
return null;
}
$data = file_get_contents($fileUrl);
}
$createdFile = $driveService->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
return $createdFile;
} catch (Exception $e) {
echo "Error: 12";
return null;
}
}
I am running this app on the Google App Engine.
However, I am unable to upload all the files I pass to it. For example, if I pass about 12-15 files, only 10-11 get uploaded, and sometimes all get uploaded, even though all parameters are correct. I have caught the exception when it fails to create a file and this says it is unable to create a file, for the files that are not uploaded. I don't see any warnings or errors in the logs on the app engine.
Am I missing something? Can someone please point me where I should be looking to correct this and make it reliable enough to upload all files given to it?
The HTTP response that I get when I try to upload 30 files is this:
PHP Fatal error: The request was aborted because it exceeded the maximum execution time
Check the http response to see the detailed reason. It might be that you are hitting the throttle limit and getting a 403 rate limit response.