Thursday 19 February 2015

How to send Attachment in Email in zend framework1 - Send PDF File

How to send Attachment in Email in zend framework1 - Send PDF File

Sending an attachment in Email is very easy in zend framework. Attachmnet can be PDF file, image file, text and excel file etc. For Different type of attachment have different types of mime type. For example pdf mime type is "application/pdf" where gif image mime type is "image/gif".

In E-commerce website, when an order is placed by customer on the online website. Customer get the order detail in form of Order PDF File, So that he can keep offline record too.


Following code snippet is for How to attach a PDF file in Email using Zend Framework.
 
  /** Must fill Following detail * */
        $emailTo = 'receipts@no-spam.ws';
        $emailToName = 'receipts Name';
        /** Must fill Following detail * */
        $emailSubject = 'This is subject';
        $emailBody = 'This is HTML Email Body';
        $fromEmail = 'fromemail@no-spam.ws';
        try {
            $config = array(
                'ssl' => 'tls',
                'auth' => 'login',
                'username' => 'SMTP_USERNAME',
                'password' => 'SMTP_PASSWORD'
            );
            $transport = new Zend_Mail_Transport_Smtp('SMTP_HOST', $config);

            $mail = new Zend_Mail();
            $mail->setBodyHtml($emailBody);
            $mail->setFrom($fromEmail);
            $mail->addTo($emailTo, $emailToName);
            $mail->setSubject($emailSubject);
            
            /**PDF Add Attachment **/
            $attachment = new Zend_Mime_Part('path to pdf file');
            $attachment->type        = 'application/pdf';
            $attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
            $attachment->encoding = Zend_Mime::ENCODING_BASE64;
            $attachment->filename    = 'order.pdf';
            $mail->addAttachment($attachment);
            /** Add Attachment **/            

            if ($mail->send($transport)) {
                echo 'Sent successfully';
            } else {
                echo 'unable to send email';
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }



Different Types of Attachment