Cakephp .xls file attachment through email component - excel

I am working with CakePHP and need to send mail with .xls file attachment.
Although I have tried a lot but didn't get success.
Note - FYI, Only PDF files are getting attached with the mails.
Please find my code below -
$this->Email->to = 'email address';
$this->Email->from = 'From email address';
$this->Email->subject = 'Subject';
$this->Email->template = 'template name';
$Path = TMP;
$fileName = 'testfile.xls';
$this->Email->filePaths = array($Path);
$this->Email->attachments = array($fileName);
$this->Email->send();
Every time when I execute this code snippet, even mails are receiving but with no attachment.

The documentation ( http://book.cakephp.org/2.0/en/core-utility-libraries/email.html#sending-attachments ) is pretty clear on that.
You need to submit it as an array with the filename as key and the path as array key "file":
$email->attachments(array(
'photo.png' => array(
'file' => '/full/some_hash.png',
'mimetype' => 'image/png',
)
));
I dont know where you got your "filePaths" attribute.

Related

Mail attachment sent by SAP to Google Sheets

Briefly, from an attachment, I am looking to retrieve the data and import it into a Google Sheets spreadsheet.
Context:
An email is sent from SAP once an hour containing an attachment. This attachment can be in ".TXT" format but also in ".XLS" format but the data remains the same (no encoding parameter is available)
A script retrieves the content of the attachment.
If the attachment is in TXT format, then the data is imported into a Google Sheets.
If the attachment is in XLS format, then the attachment is converted and the data is imported into a Google Sheets.
The email containing the attachment is deleted.
Problem:
If the attachment is in TXT format and I display the data as a string,
I get this in the console:
After convert in Spreadsheet :
But for XLS format and I display the data as a string
I get this in the console:
I presume that we can observe those "?" chars due to encoding issues ?
After convert in Spreadsheet :
Why some columns appeared and how to fix it ?
Note:
If I download the XLS file on my computer and then send it back by email and convert it, I don't get the same result as if I converted it directly from the email box. Why is this?
After Convert In Spreadsheet
My scripts :
function main(){
var mailXLS;
var mailTXT;
var mailXLSDownloaded;
var attachmentXLS;
var attachmentTXT
var attachmentXLSDownloaded;
var dataXLS;
var dataTXT;
var dataXLSDownloaded;
mailXLS = GmailApp.getMessageById( "182b5d38f39bf636" ); // XLS mail.
mailTXT = GmailApp.getMessageById( "182b63be8c849b97" ); // TXT mail.
mailXLSDownloaded = GmailApp.getMessageById( "182b6510aa9153d6" ); // XLS Downloaded mail.
attachmentXLS = mailXLS.getAttachments()[0]; // Retrieve the attachment. (XLS file)
attachmentTXT = mailTXT.getAttachments()[0]; // Retrieve the attachment. (TXT file)
attachmentXLSDownloaded = mailXLSDownloaded.getAttachments()[0]; // Retrieve the attachment. (XLS Downloaded file)
dataXLS = attachmentXLS.getDataAsString(); // Data from XLS file.
dataTXT = attachmentTXT.getDataAsString(); // Data from TXT file.
dataXLSDownloaded = attachmentXLSDownloaded.getDataAsString(); // Data from XLS Downloaded file.
Logger.log( dataXLS );
Logger.log( dataTXT );
Logger.log( dataXLSDownloaded );
}
IF attachment is TXT:
// IF attachment is TXT :
var delimiter;
var body;
var spreadsheet;
delimiter = "|";
body = Utilities.parseCsv( dataTXT, delimiter ); // 2-D Array.
spreadsheet = SpreadsheetApp.create(); // new Spreadsheet.
spreadsheet.getSheets()[0].getRange( 1, 1, body.length, body[0].length ).setValues( body ); // Retrieve data.
IF attachment is XLS:
// IF attachment is XLS :
var params;
params = {
"title" : name,
"parents" : [{ "id" : "1234"}]
};
Drive.Files.insert( params, attachment, { "convert" : true} );
Looking for someone to help me in order to get the same Data format for TXT & XLS
Thanks in advance for reading !
dataXLS = attachmentXLS.getDataAsString("UTF-16"); // Data from XLS file.
var body = Utilities.parseCsv(dataXLS,"\t");
var spreadsheet = SpreadsheetApp.create("test"); // new Spreadsheet.
spreadsheet.getSheets()[0].getRange( 1, 1, body.length, body[0].length ).setValues( body ); // Retrieve data.
The issue was the encoding of the XLS file, Apps Script needed accurate encoding format in the instruction blob.getDataAsString() default is UTF-8 and it must be UTF-16.
You just need to add "UTF-16" like blob.getDataAsString("UTF-16")

Missing part of content when automatic (crone) sending email by nodemailer

I have a strange problem. I made a small application in node.js, using nodemailer to send emails each day.
And it's working perfectly when I run it from the terminal (for testing).
But when I add a job to crontab, then emails are sent but there is missing some of the content inside.
This is my transporter conf:
// send mail with defined transport object
let info = await transporter.sendMail({
priority: 'high',
from: '"Example" <example#gmail.com>', // sender address
to: 'recip#gmail.com', // list of receivers
subject: 'Example title: '+currentDate, // Subject line
text: '', // plain text body
html: header + missing + carrierStatArr + ending,// html body
attachments: attachments
});
And code for variables to html field:
let carrierStatArr = [], attachments = [];
let header = `<h1>some text ${currentDate}</h1><div><i>some text</br>some text</i></div>`;
let missing = `<h3 style="color:red;">some text: <b>${missingArr}</b></h3>`;
for (let i in checkResultArr) {
let imgName = checkResultArr[i].file;
let correctedImgName = imgName.substring(0,16);
carrierStatArr.push(`<p>Some text <b>${checkResultArr[i].name}</b>,</br>
<span>Some text: <b>${checkResultArr[i].status}</b></span></br>
<span><img src="cid:${correctedImgName}" width="1000px"/></span>
</p>`);
}
//console.log(carrierStatArr);
attachments = checkResultArr.map((file)=>{
let pat = '/var/www/html/public_html/MM1_service/images/';
let fi = file.file;
let fit = fi.substring(0,16);
return {path: pat+file.file, cid: fit};
});
//console.log(attachments[0].path);
let ending = `<hr size="1" width="100%" color="gray"><p><i>some text</i></p>`;
Of course, there are all data in arrays. And as I wrote, when I run this code manually using terminal /node sendmail.js/ it works perfectly, email contains all the information's, text, and images.
But when the script is run automatically by the cron job, the email has only header, missing, and ending variables (and the content from arrays is there) but the rest: carrierStatArr, attachments are missing.
Why is that? Manually work, run by cron not exacly.
Note: I managed to solve my problem by using the 'node-cron' module instead of the system cron. The app is working correctly.
But still I'm curious, from an academic point, why that problem occurred.

Laravel csv file validation

I am trying to populate my users db with username and password directly form a csv file. I am successfully able to populate the db and now I want to validate if the input file is a csv or not. Any suggestion is greatly appreciated.
p.s. I am new to laravel so don't mind being thorough
You can use the laravel validation. https://laravel.com/docs/5.4/validation
$uploaded_file = Input::file('file');
$file = ['file' => $uploaded_file];
$validation = ['file' => 'required|max:10000|mimes:csv']; // update here
$validator = Validator::make($file, $validation);
$upload_path = 'uploads/leads';
if(!$validator->fails()){
if($uploaded_file->isValid()){
// do what ever you want here
}
} else {
session()->flash('error', 'Error ');
return redirect('anypath')->withInput()->withErrors($validator);
}

Attach xlsx to email with MIME::Lite

I am trying to send a email with an attached xlsx file using Excel::Writer::XLSX and MIME::Lite. The generation of the excel file works, as i can scp and open the file in Excel without any problems. When i try to open the attachment from my email client (Outlook 2013) i get this error:
"Excel cannot open the file "from_2014-06_to_2014-07.xlsx" because the
file format or file extension is not valid. Verify that the file has
not been corrupted and that the file extension matches the format of
the file."
The file size that outlook displays is 444B but its actually 95K. I have been sending xls files using Spreadsheet::WriteExcel and mime type "application/vnd.ms-excel" without any problems before.
Here is what I have tried to send the email:
sub send_mail{
my $filename = shift;
my $to_email = shift;
my $from_email = shift;
my $date = shift;
$filename = shift;
my $mail = MIME::Lite->new(
'From' => '$from_email',
'To' => $to_email,
'Subject' => "Radio/TV stats $date",
'Type' => 'multipart/mixed',
#'content-type' => 'application/zip',
#'Data' => "Here is your stuff",
);
$mail->attach(
'Type' => 'TEXT',
'Data' => "Here is your stuff",
);
$mail->attach(
#'Type' => 'application/vnd.ms-excel',
'Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Path' => $filepath,
'Filename' => $filename,
'Disposition' => 'attachement',
);
$mail->send('sendmail');
}
Can anyone please help my attach the xlsx file?
You shift twice to $filename (2nd and 6th strings) and variable $filepath is not declared. May be here error?

Drupal 6 File Handling

I am handling file upload field in a form using Drupal 6 form APIs. The file field is marked as required.
I am doing all the right steps in order to save and rename files in proper locations.
upload form
$form = array();
....
$form['image'] = array(
'#type' => 'file',
'#title' => t('Upload photo'),
'#size' => 30,
'#required' => TRUE,
);
$form['#attributes'] = array('enctype' => "multipart/form-data");
...
form validate handler
$image_field = 'image';
if (isset($_FILES['files']) && is_uploaded_file($_FILES['files']['tmp_name'][$image_field])) {
$file = file_save_upload($image_field);
if (!$file) {
form_set_error($image_field, t('Error uploading file'));
return;
}
$files_dir = file_directory_path();
$contest_dir = 'contest';
if(!file_exists($files_dir . '/' . $contest_dir) || !is_dir($files_dir . '/' . $contest_dir))
mkdir($files_dir . '/' . $contest_dir);
//HOW TO PASS $file OBJECT TO SUBMIT HANDLER
$form_state['values'][$image_field] = $file;
file_move($form_state['values'][$image_field], $files_dir."/" . $contest_dir . "/contest-". $values['email']. "-" . $file->filename);
}
else {
form_set_error($image_field, 'Error uploading file.');
return;
}
On submiting form
Form always reports an error Upload photo field is required. although files are getting uploaded. How to deal with this issue?
How to pass file information to submit handler?
your handler is wrong. You never should touch $_FILES or $_POST variables in drupal, instead you should only use the drupal tools. Said that, the implementation you should is like that:
function my_form_handler(&$form,&$form_state){/** VALIDATION FILE * */
$extensions = 'jpeg jpg gif tiff';
$size_limit = file_upload_max_size();
$validators = array(
'my_file_validate_extensions' => array($extensions),
'my_file_validate_size' => array($size_limit),
);
$dest = file_directory_path();
if ($file = file_save_upload('image', $validators, $dest)) {
//at this point your file is uploaded, moved in the files folder and saved in the DB table files
}
}
I think you'll want to use the filefield module and append it to a form, as described in:
Drupal Imagfield/Filefield in custom form
The question has a link to the solution:
http://sysadminsjourney.com/content/2010/01/26/display-cck-filefield-or-imagefield-upload-widget-your-own-custom-form
From the Drupal 6 Form API docs:
"Note: the #required property is not supported (setting it to true will always cause a validation error). Instead, you may want to use your own validation function to do checks on the $_FILES array with #required set to false. You will also have to add your own required asterisk if you would like one."
Old post, but I'm looking for something similar and figured I add that.

Resources