Search code examples
phpexcelcodeigniterphpmailer

Sending attachments with PHPMailer library


Currently I have a table where I'm displaying all my records. Now I have a functionality to export the table data to an excel sheet. Now when I click export the excel sheet goes to my C:\Xammp\htdocs folder. The following is the code I'm using to save the excel sheet.

function listing_export_allxls()
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $arrlistings = $this->input->post('listing');
        $lists = str_replace('-', ',', $arrlistings);
        $arrLists = $this->listings_model->exportallxls($lists = '');
        $sheet->setCellValue('A1', 'Listing Sales');
        $sheet->getStyle("A1")->getFont()->setSize(16);
        $i = 0;
        $row = 3;
        $Column = array('A', 'B', 'C', 'D', 'E', 'F');
        // Header
        $column_title = array('Ref No', 'Name', 'For', 'Unit No.', 'Unit Type', 'Development');
        for ($i = 0; $i <= count($column_title) - 1; $i++) {
            $index = $Column[$i] . $row;
            $sheet->setCellValue($index, $column_title[$i]);
        }
        // Rows
        for ($j = 0; $j < count($arrLists); $j++) {
            $row++;
            $sheet->setCellValue('A' . $row, $arrLists[$j]['refno']);
            $sheet->setCellValue('B' . $row, $arrLists[$j]['proptitle']);
            $sheet->setCellValue('C' . $row, $arrLists[$j]['property_for']);
            $sheet->setCellValue('D' . $row, $arrLists[$j]['unitno']);
            $sheet->setCellValue('E' . $row, $arrLists[$j]['ctitle']);
        }
        $sheet->getStyle('A3:M3')->getFill()
            ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
            ->getStartColor()->setARGB('FFA0A0A0');
        $writer = new Xlsx($spreadsheet);
        $writer->save('all_listings_' . date('dmyhis') . '.xls');
        $attachment = ($_SERVER['DOCUMENT_ROOT'] .'all_listings_' . date('dmyhis') . '.xls');
        $this->send_mail_excel('test@email.com', 'test', 'test',$attachment, '', '');
    }

Now here I'm saving the file name to $attachment and I'm writing the following in my send_email function:

function send_mail_excel($emailto, $subject, $message, $attachment, $agentemail = "", $agentname = "")
{
    require_once($_SERVER['DOCUMENT_ROOT'] . '/application/libraries/PHPMailer/src/PHPMailer.php');
    require_once($_SERVER['DOCUMENT_ROOT'] . '/application/libraries/PHPMailer/src/SMTP.php');
    require_once($_SERVER['DOCUMENT_ROOT'] . '/application/libraries/PHPMailer/src/Exception.php');

    $mail = new PHPMailer\PHPMailer\PHPMailer();

    try {
        //Server settings                   
        $mail->isSMTP();                                            //Send using SMTP
        $mail->Host = "smtp.gmail.com";                             //Set the SMTP server to send through
        $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
        $mail->SMTPSecure = 'ssl';
        $mail->Port       = 465;

        $mail->Username = "xxx";
        $mail->Password = 'xxx';
        $mail->SetFrom("xxx");
        //multiple recepients
        if (strrpos($emailto, ',') > 0) {
            $recipients = explode(',', $emailto);
            $i = 0;
            foreach ($recipients as $email) {
                if ($i == 0) {

                    $mail->addAddress($email);
                    $mail->AddCC($email);
                    if($agentemail){
                        $mail->addReplyTo($agentemail, $agentname);
                    }
                }
                ++$i;
            }
        } else {
            $mail->addAddress($emailto);
            $mail->AddCC($emailto);
            if($agentemail){
                $mail->addReplyTo($agentemail, $agentname);
            }
        }

        //Content
        $mail->isHTML(true);                                  //Set email format to HTML
        $mail->Subject = $subject;
        $mail->Body = $message;
        $mail->addAttachment($attachment);
        $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

        $mail->send();
        $msg = 'Message has been sent';
    } catch (Exception $e) {
        $msg = "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
    return $msg;
}

Now here I'm able to successfully get my email, but it only shows me the subject and message, but no attachments were attached. So where exactly am I going wrong with adding my attachment here?

EDIT: So I found out the problem. I did a print on $attachment and it showed me C:/Xammp/htdocs/all_listings_260122084136.xls meanwhile the filename in my actual folder is C:/Xammp/htdocs/all_listings_260122084135.xls. So how can I get the same filename in this case. The method I put seems to not work


Solution

  • The problem occurs because you are generating the filename twice, and it's time-dependent, so it can be different each time. Define it once in a variable and then use it for both things:

    $attachment = $_SERVER['DOCUMENT_ROOT'] .'all_listings_' . date('dmyhis') . '.xls';
    $writer->save($attachment);
    $this->send_mail_excel('test@email.com', 'test', 'test', $attachment, '', '');