print screen > ckeditor > CakePHP CakeEmail - php

I have a CKEditor 3.6.5 (revision 7647) field (on a CakePHP 2.2.1 site) where users paste print screen images (only works on Firefox). The html generated by the paste (button paste from word) is something like this:
<img alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO 9TXL0Y4OHwAAAABJRU5ErkJggg==" />
At a certain point I have to send by Email the html on these fields which should include the images.
Reading [base64-encoded-images-in-email-signatures][1] and [how-to-embed-images-in-email][2] I figured that the Email should have an attachment with the image.
My question is how can I transform the src of the image on a file? This way I intend to transform the HTML before send.
I have tried with success to attach a file with:
$data = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAUA AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO 9TXL0Y4OHwAAAABJRU5ErkJggg==');//file_get_contents('http://' . env('HTTP_HOST') . $fileInfo['url'] . '/disable-auth-key:' . Configure::read('Security.salt') . '.' . $fileInfo['ext']);
$handle = fopen(TMP . 'print_screen.png', 'w+');
fwrite($handle, $data);
fclose($handle);
$email = new CakeEmail(array(
'log' => true,
'config' => 'smtp',
'returnPath' => 'return#mydomain.pt',
'from' => array('app#mydomain.pt' => 'APP'),
'to' => array('name#domain.pt' => 'Name'),
'emailFormat' => 'html',
'subject' => 'image test',
'domain' => '#uab.pt',
'attachments' => array(
'print_screen.png' => array(
'file' => TMP . 'print_screen.png',
'mimetype' => 'image/png',
'contentId' => 'Print-Screen-01'
)
)
));
$email->send('test|<img src="cid:print_screen.png#Print-Screen-01">|');
On GMail I have access to the attachment file but on the body no image. Where is the source
<div id=":85x">test|<img>|</div>
On Outlook, no attachments and the source is
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">test|<img src="cid:print_screen.png#Print-Screen-01">
I'm also open to other solutions that achieve the same result.

on the src attribute of the image tag the cid value should be I was using #.
The correct line of code
$email->send('test|<img src="cid:Print-Screen-01">|');

Related

Drive API uploaded file always has zero size with PHP client

I'm trying to upload files into a google drive in a specific folder using a service account. It all appears to work - but the files always show up with 0 size. I've found a couple of very similar questions on here but none of the answers have worked.
The code I'm using is:
putenv('GOOGLE_APPLICATION_CREDENTIALS = ' . $home_path . '../google-oauth-credentials.json');
try {
$gclient = new Google\Client();
$gclient->useApplicationDefaultCredentials();
$gclient->addScope('https://www.googleapis.com/auth/drive');
$driveService = new Google\Service\Drive($gclient);
$content = file_get_contents('testfile.txt');
$fileMetadata = new Google\Service\Drive\DriveFile(array(
'name' => 'test.txt',
'parents' => array('{PARENT_ID}'),
'description' => 'Test Description'
));
$file = $driveService->files->create($fileMetadata, array([
'data' => $content,
'mimeType' => 'text/plain',
'uploadType' => 'multipart',
'fields' => 'id'
]));
printf("File ID: %s\n", $file->id);
echo '<br>';
echo '<pre>' . print_r($file,1) . '</pre>';
echo '<h1>Content:</h1>';
echo ($content);
} catch(Exception $e) {
echo "Error Message: ".$e;
};
With {PARENT_ID} being the ID of the folder the files should be saved in.
This is meant to be uploading pdf files but I've switched to a simple text file to rule out a mime issue. With the PDF's I was using "application/pdf" as the mimeType, I've also tried "application/octet-stream" for both pdf and text and I've tried putting the mimeType in the $fileMetaData as well as in the request body as it currently is.
I've tried using 'uploadType' of 'media' as well as some other answers had suggested.
I've also tried with and without the 'fields' => 'id' whose purpose I can't seem to find in the API docs - but which was shown in various examples and other answers. I get the same results with or without it.
No luck. With any of that I get files with correct meta data....but they never have any content and are just 0 bytes in size.
I added the lines echoing out $content to confirm that file_get_contents is loading the correct file and its content to rule out a problem with what I'm passing to the request.
I'm loading the google api client through composer with
composer require google/apiclient:^2.12.1
And it seems to be working correctly as I can create google sheets, and edit their contents as well as create files...just the files always wind up having 0 size.
Try dropping the 'uploadType' => 'multipart',
// Upload a file to the users Google Drive account
try{
$filePath = "image.png";
$fileMetadata = new Drive\DriveFile();
$fileMetadata->setName('testfile.txt');
$fileMetadata->setMimeType('text/plain');
$content = file_get_contents($filePath);
$mimeType=mime_content_type($filePath);
$request = $service->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'fields' => 'id'));
printf("File ID: %s\n", $request->id);
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
I found the problem.
The error was in:
$file = $driveService->files->create($fileMetadata, array([
'data' => $content,
'mimeType' => 'text/plain',
'uploadType' => 'multipart',
'fields' => 'id'
]));
Which came more or less verbatim from:
https://developers.google.com/drive/api/guides/manage-uploads
I'm also not sure why the 'fields' parameter is included since v3 create doesn't appear to support that.
Note the "array([])" It's defining an array inside the array.
Removing the [] or the array() solves the problem by correctly passing the intended array instead of passing an array containing the intended array.

How to get Blade template view as a raw HTML string?

I need the HTML of my Blade template as a string.
I'm going to use that HTML string to generate a PDF from it.
At the moment I have Blade streaming as a response back to browsers.
return view('users.edit', compact('user'));
How can I get the raw HTML string from the blade template?
You can call render() on the view.
$html = view('users.edit', compact('user'))->render();
See the View source code for more information.
This is the perfect solution of download/converting a blade file to HTML.
$view = view('welcome')->render();
header("Content-type: text/html");
header("Content-Disposition: attachment; filename=view.html");
return $view;
<!-- View stored in resources/views/greeting.blade.php -->
<html>
<body>
<h1>Hello, {{ $name }}</h1>
</body>
</html>
<!-- In your php controller -->
return view('greeting', ['name' => 'James']);
edited
<!-- In your PHP controller You can add html variable , and then use it for example to print PDF -->
$html=view('greeting', ['name' => 'James']);
$pdf = \App::make('snappy.pdf.wrapper');
$output = $pdf->loadHTML($html)->output();
$headers = [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="' . $filename . '"',
];
\Storage::put("pdfs/$filename", $output);
return response()->download(storage_path("app\\pdfs\\$filename"), $filename . '.pdf', $headers);
<!-- or return \Response::make($output, 200, $headers); -->
to use snappy you need to follow the instructions :
https://github.com/barryvdh/laravel-snappy
1. Download wkhtmltopdf from here https://wkhtmltopdf.org/downloads.html
2. Package Installation: composer require barryvdh/laravel-snappy
3. In (app.php) providers array add Barryvdh\Snappy\ServiceProvider::class,
4. In (app.php) aliases array add 'PDF' => Barryvdh\Snappy\Facades\SnappyPdf::class, 'SnappyImage' => Barryvdh\Snappy\Facades\SnappyImage::class,
5. Run php artisan vendor:publish --provider="Barryvdh\Snappy\ServiceProvider"
6. In (snappy.php) edit the binary path based on your installation path for wkhtmltopdf For me it is the following :
return array(
'pdf' => array(
'enabled' => true,
// base_path('vendor\wemersonjanuario\wkhtmltopdf-windows\bin\64bit\wkhtmltopdf'),
'binary' =>'"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf"',
'timeout' => false,
'options' => array(),
'env' => array(),
),
'image' => array(
'enabled' => true,
'binary' =>'"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf"',
'timeout' => false,
'options' => array(),
'env' => array(),
),
);
Will return as sting
$myViewData = View::make('test.view',compact('data'))->render();
Good luck!

Yii2 send pdf to mail not working?

I am using kartik mpdf extension to generate using the mention below code it work and show the pdf in next tab
$pdf = new Pdf([
'mode' => Pdf::MODE_UTF8, // leaner size using standard fonts
'filename' => 'Bill_of_lading_'.$exportDetail->booking_number.'_'.$customerDetail->customer_name.'_'.$customerDetail->company_name.'.pdf',
'content' => $this->renderPartial('landing', [
'model' => $this->findModel($id),
]),
'options' => [
'title' => 'Privacy Policy - Krajee.com',
'subject' => 'Generating PDF files via yii2-mpdf extension has never been easy'
],
'methods' => [
'SetHeader' => ['Generated By: ARIANA WORLDWIDE||Generated On: ' . date("r")],
'SetFooter' => ['|Page {PAGENO}|'],
]
]);
return $pdf->render();
Now for send the generatd pdf on mail i want to send the mail before save it on server using below code
$content = $pdf->content;
$filename = $pdf->filename;
$sendemail=Yii::$app->mail->compose()
->attachContent($content, [
'fileName' => $filename,
'contentType' => 'application/pdf'
])
->setFrom('mushahidh224#gmail.com')
->setTo('rajwabarocho#gmail.com')
->setSubject('Design Beta sending subject here')
->send();
Try my best to hit api and generate pdf but this also doesnt work.
$mpdf = $pdf->getApi();
$mpdf->WriteHTML($content);
$path = $mpdf->Output(Yii::getAlias('#backend').'/uploads/pdf/'.$filename.'.pdf', 'F');
It also retrn Null
First i have save the generated pdf in the server directory and then send it to mail and unlink after sending succcessfully using the below code
$pdf = new Pdf([
'mode' => Pdf::MODE_UTF8, // leaner size using standard fonts
'filename' => 'Bill_of_lading_'.$exportDetail->booking_number.'_'.$customerDetail->customer_name.'_'.$customerDetail->company_name.'.pdf',
'content' => $this->renderPartial('landing', [
'model' => $this->findModel($id),
]),
'options' => [
'title' => 'Privacy Policy - Krajee.com',
'subject' => 'Generating PDF files via yii2-mpdf extension has never been easy'
],
'methods' => [
'SetHeader' => ['Generated By: ARIANA WORLDWIDE||Generated On: ' . date("r")],
'SetFooter' => ['|Page {PAGENO}|'],
]
]);
if($mail){
$content = $pdf->content;
$filename = $pdf->filename;
// $mpdf = $pdf->getApi();
// $mpdf->WriteHtml($content);
$path = $pdf->Output($content,Yii::getAlias('#backend').'/uploads/pdf/'.$filename.'.pdf',\Mpdf\Output\Destination::FILE);
$sendemail=Yii::$app->mail->compose()
->attach(Yii::getAlias('#backend').'/uploads/pdf/'.$filename.'.pdf')
->setFrom('mushahidh224#gmail.com')
->setTo('rajwabarocho#gmail.com')
->setSubject('Design Beta sending subject here')
->send();
if($sendemail)
{
unlink(Yii::getAlias('#backend').'/uploads/pdf/'.$filename.'.pdf');
return $this->render('mailed');
}
I cant find where the exact error is but I had successfully generated pdf via mpdf with
$model= $this->findModel($id);
// get your HTML raw content without any layouts or scripts
$content = $this->renderPartial('print_salaryslip',['model'=>$model]);
// setup kartik\mpdf\Pdf component
$pdf = new Pdf([
// set to use core fonts only
'mode' => Pdf::MODE_BLANK,
// A4 paper format
'format' => Pdf::FORMAT_A4,
// portrait orientation
'orientation' => Pdf::ORIENT_PORTRAIT,
// stream to browser inline
'destination' => Pdf::DEST_BROWSER,
// your html content input
'content' => $content,
// format content from your own css file if needed or use the
// enhanced bootstrap css built by Krajee for mPDF formatting
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
// any css to be embedded if required
'cssInline' => '.kv-heading-1{font-size:18px}',
// set mPDF properties on the fly
'options' => ['title' => 'Krajee Report Title'],
// call mPDF methods on the fly
'methods' => [
'SetHeader'=>[' PAYSLIP'],
'SetFooter'=>['{PAGENO}'],
]
]);
// return the pdf output as per the destination setting
return $pdf->render();
and make sure the$contentis pure html.
Do something like this
...
if (!empty($id)) {
$emailSend = Yii::$app->mailer->compose(['html' =>'My-template-html'],[
'email' => $receiver->email,
'name' => $receiver->name
])
->setFrom(["info#mail.com"])
->setTo($email)
->setSubject($subject)
->attach(Yii::getAlias('#backend').'/web/uploads/pdf/'.'Certificate'.'.pdf');
return $emailSend->send();
Yii::$app->session->setFlash('success', 'Email Sent Successfully');
}
...

How to remove random spaces in html mail?

I see random spaces in the html mail which breaks entire html structure and gives the weird html mail.
I am using SENDY newsletter API to send mail to clients. The html mail is working fine in all other email clients like outlook express and so on.. except 'ZIMBRA' email client where I see random spaces which is leading to weird html mail.
For Ex: If image path is say http://www.example.com/12.jpg and it gives you
http://ww w.example.com/1 2.jpg
Code
$postdata = http_build_query(
array(
'api_key' => 'xxx',
'from_name' => 'xxx',
'from_email' => 'xxx',
'reply_to' => 'xxx',
'subject' => 'Daily',
'html_text' => html_content,
'list_ids' => 'hhjh',
'send_campaign' => 1
)
);
$opts = array('http' => array('method' => 'POST', 'header' => Array('Content: text/html', 'charset=UTF-8'), 'content' => $postdata));
Please help me, Thanks in advance.
Try using Trim function or try str_replace(' ','','the variable that generates the image')
I am finally able to find solution for this. I added encode property like this
$mail->encoding = base64. It worked.

uploaded file name in email subject

Below code will show file name in Email Body, but I want it to appear in Email Subject also.
Where I will put $files_list in subject ?
I tried
'subject' => __('$files_list uploaded for you','cftp_admin')
'subject' => __($files_list.'New files uploaded for you','cftp_admin'),
Not working. Here is the code :
$email_strings_file_by_user = array(
'subject' => __('New files uploaded for you','cftp_admin'),
'body' => __('The following files are now available for you to download.','cftp_admin'),
'body2' => __("If you prefer not to be notified about new files, please go to My Account and deactivate the notifications checkbox.",'cftp_admin'),
'body3' => __('You can access a list of all your files or upload your own','cftp_admin'),
'body4' => __('by logging in here','cftp_admin')
);
function email_new_files_for_client($files_list)
{
global $email_strings_file_by_user;
$this->email_body = $this->email_prepare_body('new_file_by_user');
$this->email_body = str_replace(
array('%SUBJECT%','%BODY1%','%FILES%','%BODY2%','%BODY3%','%BODY4%','%LINK%'),
array(
$email_strings_file_by_user['subject'],
$email_strings_file_by_user['body'],
$files_list,
$email_strings_file_by_user['body2'],
$email_strings_file_by_user['body3'],
$email_strings_file_by_user['body4'],
BASE_URI
),
$this->email_body
);
return array(
'subject' => $email_strings_file_by_user['subject'],
'body' => $this->email_body
);
}
your __(.....) function probably is used for language translations, so append the variable $files_list with translation, as change:
'subject' => __($files_list.'New files uploaded for you','cftp_admin'),
to
'subject' => $files_list . __('New files uploaded for you','cftp_admin'),

Categories