9

in a custom module, I use this function to send Emails:

public function sendMail($errorCod, $errorMsg) {

    $mail = Mage::getModel('core/email');

    $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')
    );

    foreach ($recipients as $recipient):
        $mail->setToEmail($recipient);

        $mailBody  = "<b>Error Code: </b>".$errorCod."<br />";
        $mailBody .= "<b>Error Massage: </b>".$errorMsg."<br />";

        $mail->setBody($mailBody);
        $mail->setSubject('Lorem Ipsum');
        $mail->setFromEmail(Mage::getStoreConfig('trans_email/ident_general/email'));
        $mail->setFromName("Lorem Ipsum");
        $mail->setType('html');

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

    endforeach;

}

I try to send 2 attachements files in the same E-mail.

How can I do that, without using the Mage_Core_Model_Email_Template Model.

Thanks a lot for help.

14

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);
    }
}
  • Exactly, I also implemented this functionallity with Zend_Mail some time ago. – Anna Völkl Nov 17 '13 at 19:13
  • The only issue I have with this is if you're on a shared hosting server, regardless of if you set a sender, it is not the permitted sender of the server itself (if you look at the email headers for Received-SPF: – Moose Jun 4 '14 at 7:38
  • Magento already handles sending emails with attachments, I don't find it relevant to bypass its functions – DependencyHell Apr 4 at 10:23
6

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';
}
3

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('sender@sender.email');
  $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('toemail@email.com','subject','set message');
  • thanks it is working. But what is the use of 'subject' and 'set message' in the last line because as I can see the subject is already set line 4 and message is set on line 5? – Sarvagya Aug 13 '18 at 11:27
  • thanks @prince your code used for me in observer :) – Rakesh Donga Feb 8 at 9:47
  • Yes, no need to use Zend_Mail directly – DependencyHell Apr 4 at 10:22
2

//1 I used a request quote folder as requestquote in media directory for saving // uploaded images

//2 There is an array of custom variables to be passed to transactional email //email template was created in magento admin and its template id 3

//Code has been tested on Magento 1.9.1.0

//Code starts just below

$uploadfilename = '';

if( !empty($_FILES["rfloorplanattachment"]["name"])  )
{

    $image_ext = end(explode('.',$_FILES["rfloorplanattachment"]["name"]));
    $allowed_ext =  array('gif','png' ,'jpg','jpeg','pdf','doc','docx','rtf','odt');

    $uploadfilename = md5(substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(1,100).rand(1,100))).str_replace(" ","_",$_FILES["rfloorplanattachment"]["name"]); 
    $source_upl         = $_FILES["rfloorplanattachment"]["tmp_name"];
    $target_path_upl = Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename;  
    if(in_array($image_ext ,$allowed_ext ) ) {
        @move_uploaded_file($source_upl, $target_path_upl);
    }
}


$senderName = Mage::getStoreConfig('trans_email/ident_general/name');
$senderEmail = Mage::getStoreConfig('trans_email/ident_general/email');

$templateId = 3;
$sender = Array('name' => $senderName,'email' => $senderEmail);


$requestquotesvars = array(
            'firmname'     =>  $customer->getFirstname()
        );


$emaiName = 'Request Quote Firms';

$storeId = Mage::app()->getStore()->getId();

$translate = Mage::getSingleton('core/translate');
$transactionalEmail = Mage::getModel('core/email_template');
if(file_exists(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename) )
{
$transactionalEmail->getMail()
                ->createAttachment(
        file_get_contents(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename),
        Zend_Mime::TYPE_OCTETSTREAM,
        Zend_Mime::DISPOSITION_ATTACHMENT,
        Zend_Mime::ENCODING_BASE64,
        basename($uploadfilename)
    );
}
$transactionalEmail->sendTransactional($templateId, $sender, $companymail, $emailName, $requestquotesvars, $storeId);
$translate->setTranslateInline(true);

   unlink(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename);
1

Enjoy: Working example

$mail = new Zend_Mail();
$mail->setType(Zend_Mime::MULTIPART_RELATED);
$mail->setBodyHtml($html_body);
$mail->setFrom('support@example.com', 'Example');
$mail->addTo('your_email@gmail.com', 'Arslan');
$mail->setSubject('Sending email using Zend Framework');
$dir = Mage::getBaseDir();
$path = "test.html";  // any file named test.html at root
$file = $mail->createAttachment(file_get_contents($path));
$file ->type        = 'text/csv';
$file ->disposition = Zend_Mime::DISPOSITION_INLINE;
$file ->encoding    = Zend_Mime::ENCODING_BASE64;
$file ->filename    = 'test.html';
try {
    //Confimation E-Mail Send
    $mail->send();
}
catch(Exception $error) {
    Mage::getSingleton('core/session')->addError($error->getMessage());
    return false;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.