Sendgrid and laravel 5.1 store inbound attachments - php

I'm currently using Laravel and sendgrid in an application of mine.
I want to be able to receive emails with attachements and store them on the server. But the problem here is, HOW should I do this? I currently have a code written, but that code isn't working at all. I can receive the emails, but it doesn't store the attachments. Can someone help me out?
Here is the code I currently have:
public function ReceiveMail(Request $request)
{
//inserting the email into the database
// getting all of the post data
$files = $request->get('attachments');
// Making counting of uploaded images
$file_count = count($files);
//var_dump($files);
//die;
if($file_count > 0){
foreach($files as $key=>$value) {
$attachment[] = $value;
$destinationPath = 'public/uploads/pictures/rallypodium/website/mail/attachments/';
$extension = $attachment->getClientOriginalExtension();
$filename = $attachment->getClientOriginalName();
$uploadSuccess = $attachment->move($destinationPath, $filename.$extension);
}
}
return '250';
}

Related

Laravel 4.2 Input::file

Trying to upload file to my test api. For testing I tried to check if input has file and it returns true. The problem is when the code tries to move that file. Search google show almost the same code that I have;
if (Input::hasFile('attachments')) {
$path = base_path().'/assets';
$files = Input::file('attachments');
$data = [];
foreach ($files as $file) {
$data[] = $file->getClientOriginalExtension();
$uuid = Uuid::uuid1();
$extension = $file->getClientOriginalExtension();
$filename = $uuid.'.'.$extension;
$file->move($path, $filename);
}
return Response::json($data);
} else {
return 'no file';
}
Doing a post request using Paw multipart give this result on json
Still can't figure this out. Any help will be much appreciated. Thank you so much guys in advance.
Ok; so something as simple as this [] gave me a hard time figuring things out. All I did is add []; instead of just attachments I did attachments[] as post request name and in my controller I retain the Input::file('attachments')
Thank you guys for your guidance and help. Figured things out the hard and tired way.
I don't know why you are trying to iterate but there is no reason to and $files is a single uploaded file.
Just remove the loop since there is nothing to iterate.
if (Input::hasFile('attachments')) {
$path = base_path().'/assets';
$file = Input::file('attachments');
$uuid = Uuid::uuid1();
$extension = $file->getClientOriginalExtension();
$filename = $uuid.'.'.$extension;
$file->move($path, $filename);
return Response::json($extension);
} else {
return 'no file';
}
If you wanted to have multiple files you would need to have the input setup to be named as an array, attachments[]. You are sending attachments which is always a single value. If you sent an array then there would potentially be something for you to iterate through.

PHP: SendGrid mail attachments from S3 server

I need to be able to send one, maybe more, files stored on an Amazon S3 server as attachments in an email created using SendGrid.
The problem I have is that I'm not a web dev expert and the sparse PHP examples I can find are not helping me much.
Do I need to download the files from the S3 server to the local /tmp directory and add them as attachments that way, or can I pass the body of the file from the FileController and insert it as an attachment that way?
I'm not really sure where to start, but here's what I've done so far:
$attachments = array();
// Process the attachment_ids
foreach($attachment_ids as $attachment_id) {
// Get the file if it is attached to the Activity
if (in_array($attachment_id, $activity_file_ids)) {
$file = File::find($attachment_id);
$fileController = new FileController($this->_app);
$fileObject = $fileController->getFile($attachment_id);
error_log(print_r($fileObject, true));
$attachment = array();
$attachment['content'] = $fileObject;
$attachment['type'] = $fileController->mime_content_type($file->file_ext);
$attachment['name'] = explode(".", $file->filename, 2)[0];
$attachment['filename'] = $file->filename;
$attachment['disposition'] = "inline";
$attachment['content_id'] = '';
}
}
My next step would be to push the $attachment array to the $attachments array. Once $attachments is complete, iterate through it and add each $attachment to the SendGrid e-mail object (the e-mail is working fine without attachments, btw.)
Problem is, I'm not sure I'm going down the right road with this or if there's a much shorter and neater (and working) way of doing it?
FileController->getFile() essentially does this:
$file = $this->_s3->getObject(array(
'Bucket' => $bucket,
'Key' => $filename,
));
return $file['Body'];
Any help (especially code examples) would be greatly appreciated!
Okay, I've got a working solution to this now - here's the code:
// Process the attachment_ids
foreach($attachment_ids as $attachment_id) {
// Get the file if it is attached to the Activity
if (in_array($attachment_id, $activity_file_ids)) {
// Get the file record
$file = File::find($attachment_id);
// Get an instance of FileController
$fileController = new FileController($this->_app);
// Set up the Attachment object
$attachment = new \SendGrid\Attachment();
$attachment->setContent(base64_encode($fileController->getFile($attachment_id)));
$attachment->setType($fileController->mime_content_type($file->file_ext));
$attachment->setFilename($file->filename);
$attachment->setDisposition("attachment");
$attachment->setContentId($file->file_desc);
// Add the attachment to the mail
$mail->addAttachment($attachment);
}
}
Don't know if it will help anybody else, but there it is. The solution was to get the file from the S3 server and pass base64_encode($file['Body']) to the setContent function of an instantiated Attachment object, along with setting a few other fields for it too.

File upload not working with laravel $file on some machine

In my Laravel project I created a page to upload the files and I use the $file of laravel it works fine for some system only but for some system it shows an error as shown in image below.
Function I am using to upload files in model
public function add_document_sub_cert($req)
{
$subcontractor_id = $req['subcontractor_id'];
$reference_id = $req['reference_id'];
$files = $req->file("uploaded_doc0");
$i = 0;
foreach($files as $file){
$i++;
$ext = $file->guessClientExtension();
$name = $file->getClientOriginalName();
$file_name_1 = str_replace(".".$ext,"",$name);
$path = $file->storeAs('subcontractor/','avc'.$i.'.jpg');
if($path){
$document = new Document();
$document->doc_name = 'avc.jpg';
$document->module = 'subcontractor';
$document->reference_id = $reference_id;
$document->save();
}
}
}
Your error says that you didn't specify a filename. I see that your variable $file_name_1 is never used. Haven't you forgotten to use it somewhere?
Without knowing how your class Document works, it's impossible to tell you exactly where is the bug.

How to insert Multiple Uploaded files to database

I'm working on a mobile application, and I'm handling database and APIs.
Android developer is sending me images and I'm using file function to get its data.
I have written this code:
public function addalbum($baseurl)
{
$images = array();
if(isset($_FILES['image'])){
//echo "hellow";exit;
//$pathToUpload = '../media/gallary/';
$count = count($_FILES['image']['name']);
//echo $count;exit;
$imagepaths = '';
$imagetepaths = '';
$images = '';
for($i=0;$i<$count;$i++){
$imageurls[$i] = $baseurl."../media/gallary/".$_FILES['image']['name'];
$imagepaths = '../media/gallary/'.$_FILES['image']['name'][$i];
$images[$i] = $_FILES['image']['name'][$i];
$imagetepaths = $_FILES['image']['tmp_name'][$i];
move_uploaded_file($imagetepaths , $imagepaths);
}
}
$data=array(
'image' => ($images != '') ? implode(',',$imageurls) : '',
'email'=>$this->input->post('email'),
'name'=>$this->input->post('name'),
'type'=>$this->input->post('type')
);
//print_r($data);exit;
$this->db->insert('album',$data);
}
But from the bunch of images, only the last one is being inserted in the database.
any help will be very much appreciated.
Thanks
$_FILES['image'] is the field name of 1 uploaded file. If multiple files should be posted you would require different names for each field. Just think how will you upload multiple files from an html form.
For example: $_FILES['image1'], $_FILES['image2'], $_FILES['image3']
You could use something like this:
if(is_array($_FILES)) {
foreach($_FILES as $fileKey => $fileVal){
if($fileVal[name]) {
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],$target_path.$fileVal[name]);
}
}
}
Checkout this example where a maximum of 3 files are uploaded from android using php.

Moving Attachments To Folder And Attaching Them With Email

I have a simple page, which is sending an Email message and multiple attachments, through phpmailer.
I have to attach the multiple attachments to the Email message to send, and also upload these files o server at same time, For which i m using the following loop:
$MyUploads = array();
foreach(array_keys($_FILES['attach']['name']) as $key)
{ $Location="uploads/";
$name=$_FILES['attach']['name'][$key];
$filePath = $Location . $name;
$source = $_FILES['attach']['tmp_name'][$key]; // location of PHP's temporary file for
$tmp=$_FILES['attach']['tmp_name'][$key];
if($mail->AddAttachment($source, $name))
{if(move_uploaded_file($tmp, $filePath)){
$MyUploads[] = $filePath;}
else
{$MyUploads[]='';
echo "not uploaded";}
}
}
The problem is, when i use the function move_uploaded_file(), the files are uploaded to the server folder, but are not sent with the attachments. As i comment out this function the attachments are sended.
Can;t find out, why these two dnt work together. Please any body help
Here is the loop that sends Attachments, And move them to a target path, for further use. I hope any one else can be helped by this:
$MyUploads = array();
$numFiles = count(array_filter($_FILES['attach']['name']));
for ($i = 0; $i < $numFiles; ++$i) {
$target_path = 'uploads/' . basename($_FILES['attach']['name'][$i]);
if(move_uploaded_file($_FILES['attach']['tmp_name'][$i], $target_path)) {
echo "the file ".basename($_FILES['attach']['name'][$i])." has been uploaded<br />";
$MyUploads[] = $target_path;
echo $MyUploads;
$mail->AddAttachment($target_path);
}
}

Categories