Attach xlsx to email with MIME::Lite - excel

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?

Related

Import excel file to database using Laravel

why get undefined offset when importing excel file to the database using laravel.
UserImport.php
public function model(array $row)
{
var_dump($row);
return new User([
'name' =>$row[0],
'email'=>$row[1],
'password' => Hash::make('password'),
]);
}
UserImportController
public function store(Request $request){
$file = $request->file('file');
Excel::import(new UsersImport, $file);
return back()->withStatus('Successfully');
}
when uploading the excel file, display it like this.
enter image description here
I used var_dump() to see the array. I entered 4 rows in the excel file. But display 5 array data. Why that??? (display in entered image.
)
I believe it is because of the new line at the end of the file.
You should check if it contains only a new line and skip the import.
set if condition for UserImport.php
if($row[0] !=""){
return new User([
'name' =>$row[0],
'email'=>$row[1],
'password' => Hash::make('password'),
]);
}

Converting XLSX to CSV with Perl while maintaining the encoding

I'm a BI developer working with perl scripts as my ETL - I receive data over email, take the file, parse it and push it into the DB.
Most of the files are CSV, but occasionally I have an XLSX file.
I've been using Spreadsheet::XLSX to convert, but I've noticed that the CSV output comes out with the wrong encoding (needs to be UTF8, because accents and foreign languages).
That's the sub I'm using ($input_file is an Excel file), but I keep getting the data with the wrong characters.
WHAT am I missing?
Thanks a lot all!
sub convert_to_csv {
my $input_file = $_[0];
my ( $filename, $extension ) = split( '\.', $input_file );
open( format_file, ">:**encoding(utf-8)**", "$filename.csv" ) or die "could not open out file $!\n";
my $excel = Spreadsheet::XLSX->new($input_file);
my $line;
foreach my $sheet ( #{ $excel->{Worksheet} } ) {
#printf( "Sheet: %s\n", $sheet->{Name} );
$sheet->{MaxRow} ||= $sheet->{MinRow};
foreach my $row ( $sheet->{MinRow} .. $sheet->{MaxRow} ) {
$sheet->{MaxCol} ||= $sheet->{MinCol};
foreach my $col ( $sheet->{MinCol} .. $sheet->{MaxCol} ) {
my $cell = $sheet->{Cells}[$row][$col];
if ($cell) {
my $trimcell;
$trimcell = $cell->value();
print STDERR "cell: $trimcell\n"; ## Just for the tests so I don't have to open the file to see if it's ok
$trimcell =~ s/^\s+|\s+$//g; ## Just to make sure I don't have extra spaces
$line .= "\"" . $trimcell . "\",";
}
}
chomp($line);
if ($line =~ /Grand Total/){} ##customized for the files
else {
print format_file "$line\n";
$line = '';
}
}
}
close format_file;
}
My knowledge is from using ETL::Pipeline and it uses Spreadsheet::XLSX for reading .xlsx-files.
But I know which fields are UTF-8
I wrote a Local ETL::Pipeline module to handle output for Excel files
use Encode qw(decode encode);
$ra_rec->{name} = decode( 'UTF-8', $ra_rec->{name}, Encode::FB_CROAK );

Perl/Tk invoking a batch command and passing argument

I have to prepare a GUI , where the Perl/Tk should invoke a batch command (a local one with path hardcoded) and passing argument (which is the .csv file selected by the user) -When user presses the GENERATE button-here simplified as just opening the .csv file in notepad . Can someone help me ?
use Tk;
my $my_MW=MainWindow->new();
$my_MW->title("Sample application");
$my_MW->geometry("350x180-500+500");
$my_MW->resizable( 'no', 'no' );
my $my_Button=$my_MW->Button(-text=>"Select CSV Input File",-command=> \&get_file);
$my_Button->pack(-side=>"top",-expand=>1,-anchor=>"w",-padx => 20,-pady => 20);
my $filepath=" .... ";
my $my_Entry=$my_MW->Entry(-textvariable=> \$filepath);
$my_Entry->pack(-side=>"top",-expand=>1,-anchor=>"w",-padx => 20,-pady => 0,-fill=>"x");
my $my_Button1=$my_MW->Button(-text=>"GENERATE",-width => 12,-command=>sub{\&gen_rslt()});
$my_Button1->pack(-side=>"left",-expand=>1,,-pady => 20);
$my_Button1->configure(-state => 'disabled');
my $my_Button2=$my_MW->Button(-text=>"RESET",-width => 12,-command=>sub{\&clear_field()});
$my_Button2->pack(-side=>"left",-expand=>1,,-pady => 20);
my $my_Button3=$my_MW->Button(-text=>"EXIT",-width => 12,-command=>sub{exit()});
$my_Button3->pack(-side=>"left",-expand=>1,,-pady => 20);
MainLoop();
sub gen_rslt{
#Call the batch file and pass the file path as an argument!
#batch file to open the file in notepad
}
sub clear_field{
$my_Entry->delete(0,'end');
$my_Entry->insert(0," .... ");
$my_Button1->configure(-state => 'disabled');
}
sub get_file
{
$my_Entry->delete(0,'end');
my #types =
(["comma seperated files", [qw/.csv/]],
["All files", '*'],
);
$filepath = $my_MW->getOpenFile(-filetypes => \#types) or return();
$my_Button1->configure(-state => 'normal');
}
using system command you can open the file.
example is
system("notepad.exe myfile.txt");
or also you can use as follows
system(notepad.exe, $filepath);

Cakephp .xls file attachment through email component

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.

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