Asked  7 Months ago    Answers:  5   Viewed   135 times

I have a site where in a page I have developed an xls report. After its creation I want to send it in a mail with phpmailer. How can I attach this file to the email? This is my code:

    $objPHPExcel = new PHPExcel();

            // Set document properties
            $objPHPExcel->getProperties()->setCreator("Alessandro Minoccheri")
                                         ->setLastModifiedBy("Alessandro Minoccheri")
                                         ->setTitle("Office 2007 XLSX Test Document")
                                         ->setSubject("Office 2007 XLSX Test Document")
                                         ->setDescription("Generazione report inverter")
                                         ->setKeywords("office 2007 openxml php")
                                         ->setCategory("");

            $row=1;
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow('0', $row, 'Inverter');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow('1', $row, 'Channel');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow('2', $row, 'Picco');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow('3', $row, 'Picco data');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow('4', $row, 'Media');
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow('5', $row, 'Sommatoria');
$objPHPExcel->setActiveSheetIndex(0);

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('report.xls');

               $yourName = 'Client';
        $yourEmail_2 = 'alessandro@xxx-it';

        ini_set("include_path", "../inc/phpmailer/");
        require("class.phpmailer.php");
        $mail = new PHPMailer();

        $mail->From     = 'xxx@xxx.com';
        $mail->FromName = 'Client';
        $mail->AddAddress($yourEmail_2); 
        //$mail->AddBCC($yourEmail_2); 

        /*if(!empty($_FILES['attachment']['tmp_name'])){
            $new_name = urlencode( rand(0,10000).rand(10000,20000).$_FILES['attachment']['name'] );
            if(move_uploaded_file($_FILES['attachment']['tmp_name'],'./uploads/'.$new_name)){
                $string_file = '<p>Curriculum allegato: '</p>';
            }
        }*/

        $mail->WordWrap = 50;                              // set word wrap
        $mail->IsHTML(true);                               // send as HTML

        $mail->Subject  =  'Riepilogo settimanale';

        $mail->Body     =  "Riepilogo settimanale dell'impianto: ".utf8_decode($inv['name']);

        $mail->AltBody  =  "Riepilogo settimanale dell'impianto: ".utf8_decode($inv['name']);

        if ( $mail->Send()){
            //ok
        }

 Answers

80

Have you tried...

$mail->AddAttachment($full_path_to_file, "report.xls");
Saturday, May 29, 2021
 
Len_D
answered 7 Months ago
44

Here is another possible way without re-creating the Class each time.

<?php

require 'phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();                                      // Set mailer to         use SMTP
$mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'yyy.com';                 // SMTP username
$mail->Password = 'yyy';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                    // TCP port to connect to
$person = array(0 => 'xxx.com', 'xxx2.com');

$mail->setFrom('yyy.com');
$mail->isHTML(true);                                  // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body    = "xxx";
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

$errors = [];
for ($x = 0; $x < 2; $x++) {
    $mail->addAddress($person[$x]);
    if(!$mail->send()) {
        $errors[] = 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
    }
    $mail->clearAddresses();
}

if(empty($errors)) {
    // success
} else {
    // handle errors
}

Using $mail->clearAddresses(); within the loop.

Wednesday, March 31, 2021
 
Palladium
answered 9 Months ago
33

EDIT I added a pull request with a fix: https://github.com/PHPOffice/PHPExcel/pull/251

This happens when you try to duplicate cell's style to the same cell; Take a look at this:

$phpe = new PHPExcel();
$sheet = $phpe->createSheet();

$sheet->setCellValue('A1', 'hi there') ;
$sheet->setCellValue('A2', 'hi again') ;

$sheet->duplicateStyle($sheet->getStyle('A1'), 'A2');

$writer = new PHPExcel_Writer_Excel2007($phpe);
$writer->save('./test.xlsx');

It will work just fine. BUT if I add another line like this:

$sheet->duplicateStyle($sheet->getStyle('A1'), 'A1');

then bang, infinite recursion starts after calling the save method

To fix your code, you should modify this part:

$sheet->duplicateStyle((($level == 0) ?  $this->styles['category'] : $this->styles['subcategory']), Cell::NUMBER . $row);

To something along the lines of:

$style = ($level == 0) ?  $this->styles['category'] : $this->styles['subcategory'];
$targetCoords = Cell::NUMBER . $row;
if($style->getActiveCell() != $targetCoords) {
    $sheet->duplicateStyle($style, $targetCoords);
}
Saturday, May 29, 2021
 
rblarsen
answered 7 Months ago
38

It is pretty simple, leave the images on the server and send the PHP + CSS to them...

$to = 'bob@example.com';

$subject = 'Website Change Reqest';

$headers = "From: " . strip_tags($_POST['req-email']) . "rn";
$headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "rn";
$headers .= "CC: susan@example.comrn";
$headers .= "MIME-Version: 1.0rn";
$headers .= "Content-Type: text/html; charset=UTF-8rn";

$message = '<p><strong>This is strong text</strong> while this is not.</p>';


mail($to, $subject, $message, $headers);

It is this line that tells the mailer and the recipient that the email contains (hopefully) well formed HTML that it will need to interpret:

$headers .= "Content-Type: text/html; charset=UTF-8rn";

Here is the link I got the info.. (link...)

You will need security though...

Tuesday, June 1, 2021
 
TMichel
answered 7 Months ago
82

I suspect it might be confusing that you are uploading it as form-encoded. but that isn't what you are sending (unless you're glossing over something). Is that MIME type really correct?

How big is the data? Do you need chunked upload? Some servers might not like this in a single request; I'd be tempted to use multiple simple requests via WebClient.UploadData.

Saturday, August 14, 2021
 
SpiderLinked
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share