Magento : send file attachements in Emails
Try to use Zend_Mail. See:
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('Lorem Ipsum')
->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,
'attachment_1.log'
);
$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,
'attachment_2.log'
);
try {
$mail->send();
} catch (Exception $e) {
Mage::logException($e);
}
}
Just to get another answer here you can also rewrite Mage/Core/Model/Email/Template.php
and create an addAttachment
function. This example will add a pdf but you can extend this to make it work with any file type.
public function addAttachment(Zend_Pdf $pdf){
$file = $pdf->render();
$attachment = $this->getMail()->createAttachment($file);
$attachment->type = 'application/pdf';
$attachment->filename = 'yourfile.pdf';
}
Copy this code in any phtml or controller to send mail with attachment file:
$mailTemplate = Mage::getModel('core/email_template');
$mailTemplate->setSenderName('Sender Name');
$mailTemplate->setSenderEmail('[email protected]');
$mailTemplate->setTemplateSubject('Subject Title');
$mailTemplate->setTemplateText('Body Text');
// add attachment
$mailTemplate->getMail()->createAttachment(
file_get_contents(Mage::getBaseDir('base') . '/media/file/file.pdf'), //location of file
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
'file.pdf'
);
$mailTemplate->send('[email protected]','subject','set message');