
MAGENTO 1.X – SEND AN EMAIL WITH A PDF ATTACHED PROGRAMMATICALLY
On a Magento project, the easiest way to send an email with an attachment, is using the Zend library (provided by Magento).
- To do so, let’s do the following:
12345678910111213141516171819202122232425262728293031323334353637383940private function sendEmailToSomeone($mailTo, $pdf_encoded){$b64file = $pdf_encoded;if ($b64file){$b64file= trim(str_replace('data:application/pdf;base64,', "", $b64file) );$b64file= str_replace( ' ', '+', $b64file);$decodPdf= base64_decode($b64file);$pdfFileName = "Your_filename.pdf";file_put_contents($nomPdf, $decodPdf);$mail = new Zend_Mail();$recipients = array($customerName => $mailTo);$body = "<b>Body of you email in HTML</b>";$mail->setBodyHtml($body)->setSubject("Subject of your email")->addTo($recipients)->setFrom("", "");$attachment = file_get_contents($pdfFileName);$mail->createAttachment($attachment,Zend_Mime::TYPE_OCTETSTREAM,Zend_Mime::DISPOSITION_ATTACHMENT,Zend_Mime::ENCODING_BASE64,$pdfFileName);try {$mail->send();} catch (Exception $e) {Mage::logException($e);}}}
Another way to do this, is with the PHPMailer library, but it’s external and not provided by Magento (so i do not recommend using it on Magento projects).
To load the PHPMailer library, you can download it from its github repository https://github.com/PHPMailer/ , and then locate the file PHPMailerAutoload.php under app/lib/ directory.Then, you need to make a function as follows:
123456789101112131415161718192021222324252627private function sendEmailToSomeone($mailTo,$nameTo, $pdf_encoded){require 'lib/PHPMailerAutoload.php';$b64file = $pdf_encoded;if ($b64file){$b64file= trim(str_replace('data:application/pdf;base64,', "", $b64file) );$b64file= str_replace( ' ', '+', $b64file);$decodedPdf= base64_decode($b64file);$pdfName = "your_pdf_filename.pdf";file_put_contents($pdfName, $decodedPdf);$mail = new PHPMailer;$mail->isSendmail();$mail->setFrom('', '');$mail->addAddress($mailTo, $nameTo);//Set the subject line$mail->Subject = "This will be your subject";$mail->IsHTML(true);$mail->Body = "<b>This will be the body in HTML</b>";$mail->AltBody = '';$mail->addAttachment($pdfName);$mail->Timeout=60;$mail->send();}} - Once you have your function created, you can call it doing:
12345678910111213// Encode your local pdf file in a 64 bits format$pdf_base64 = "localfile.pdf";// Get File content from txt file$pdf_base64_handler = fopen($pdf_base64,'r');$pdf_content = fread ($pdf_base64_handler,filesize($pdf_base64));fclose($pdf_base64_handler);// Encode pdf content$pdf_encoded = base64_encode($pdf_content);// Call your function to send the email$this->sendEmailToSomeone('anyone@domain.com', $pdf_encoded)