Magento : send file attachments in Emails

Below code can be used to Send file attachement in emails with magento, bascially we will use zend email to do so.

public function sendMail($errorCod = "", $errorMsg = "")
{

    $mail = new Zend_Mail('utf-8');

    $recipients = array(
        Mage::getStoreConfig('trans_email/ident_custom1/name') => Mage::getStoreConfig('trans_email/ident_custom1/email'),
        Mage::getStoreConfig('trans_email/ident_custom2/name') => Mage::getStoreConfig('trans_email/ident_custom2/email'),
    );
    $mailBody   = "<b>Error Code: </b>" . $errorCod . "<br />";
    $mailBody .= "<b>Error Massage: </b>" . $errorMsg . "<br />";
    $mail->setBodyHtml($mailBody)
        ->setSubject('My Subject')
        ->addTo($recipients)
        ->setFrom(Mage::getStoreConfig('trans_email/ident_general/email'), "FromName");

    //file content is attached
    $file       = Mage::getBaseDir('var') . DS . 'log' . DS . 'exception.log';
    $attachment = file_get_contents($file);
    $mail->createAttachment(
        $attachment,
        Zend_Mime::TYPE_OCTETSTREAM,
        Zend_Mime::DISPOSITION_ATTACHMENT,
        Zend_Mime::ENCODING_BASE64,
        'myattach.txt'
    );
    $file       = Mage::getBaseDir('var') . DS . 'log' . DS . 'system.log';
    $attachment = file_get_contents($file);
    $mail->createAttachment(
        $attachment,
        Zend_Mime::TYPE_OCTETSTREAM,
        Zend_Mime::DISPOSITION_ATTACHMENT,
        Zend_Mime::ENCODING_BASE64,
        'myattach2.txt'
    );

    try {
        $mail->send();
    } catch (Exception $e) {
        Mage::logException($e);
    }
}

Hope this helps…Happy Coding!!!

(Visited 55 times, 1 visits today)