search
top

Add attachment to order email in Magento

Many times there arise the need to attach files to the order mail.

I am giving here a brief explanation for this:

I have used Magento ver. 1.7.0.0 ( In previous version there was no mailer class).

1) Rewrite Sales Class

Copy the file found at app\code\core\Mage\Sales\Model\Order.php to app\code\local\Mage\Sales\Model\Order.php
Overwrite the `sendNewOrderEmail()’ method found.
Here you need to compose the attachment
Copy the below code and paste it just before $mailer->send();
I am attaching a simple pdf file which is inside var/docs/abc.pdf


 		//(by dw)
        //start
        $dir = Mage::getBaseDir();
		$file_name = $dir.DS.'var'.DS.'docs'.DS.'abc.pdf'; //file path
		if(file_exists($file_name))
		{
			$fileContents = file_get_contents($file_name);
			$fileName = 'abc.pdf';
			$mailer->addAttachment($fileContents, $fileName);
		}
		//end

2) Rewrite mailer
Copy the file found at app\code\core\Mage\Core\Model\Email\Template\Mailer.php to app\code\local\Mage\Core\Model\Email\Template\Mailer.php

Add a function and define a protected variable in class Mage_Core_Model_Email_Template_Mailer

	protected $_afile = array(); //(by dw)

 	//custom (by dw)
    //start
    public function addAttachment($fileContents,$fileName)
    {
    	$tmp = array();
    	$tmp['fileContents'] = $fileContents;
    	$tmp['fileName'] = $fileName;
        $this->_afile = $tmp;
        return $this;
    }
    //end

Add code in send() method. In this method you will need to pass array of attachements
Add below metioned lines just before $emailTemplate->setDesignConfig…

    if(!empty($this->_afile))
    {
    	$emailTemplate->setEmAttachments($this->_afile); //(by dw)
    }

3) Rewrite Template
Copy the file found at app\code\core\Mage\Core\Model\Email\Template.php to app\code\local\Mage\Core\Model\Email\Template.php

Add below mentioned methods and define a protected variable.

    protected $_filedata = array(); //(by dw)        
    //(by dw)
    //start

    public function setEmAttachments($attachments)
    {
    	$this->setOrderAttachments($attachments);
    }

    public function getEmAttachments()
    {
        return $this->getOrderAttachments();
    }

    public function setOrderAttachments($attachments)
    {   
    	$this->_filedata = $attachments;        
        return $this;
    }

    public function getOrderAttachments()
    {    	
        return $this->_filedata;
    }
    //end

Add below mentioned code in send() method just before $mail->send() as shown.


 	//(by dw)
	//start
	$atInfo = $this->getEmAttachments();
	if(!empty($atInfo))
	{
		$_file = $mail->createAttachment($atInfo['fileContents']);
		$_file->type = 'application/pdf'; //the type should be as per your file
		$_file->filename = $atInfo['fileName'];
	}
	//end

	try {
            $mail->send();
            $this->_mail = null;
        }

GitHub : Email Attachment

Put the code in site_root/app/code/

Hope this is helpful.

For further read – Email with attachment in Magento

39 Responses to “Add attachment to order email in Magento”

  1. Vinaya says:

    This article working for me but this only can attach local files. How to attach files from another server or any other file with complete url like “http://domain.com/files/name.pdf”?
    And Similarly How to add “png” file with order email?

    • Decrypt Web says:

      – For files found in other server, if its access publicly simply add a link in the order mail, if not than download the files in your server using file functions and attach it.
      – For png, $_file->type needs to be changed, it should work

  2. Rakesh says:

    How do i add different files to different order compeltion emails, i.e select file when i process the order/change its status as completed.

    • You need to make a relation of the order with the file you need to send, are the files dynamically generated or it exists ?

      • Rakesh says:

        Those are not generated files, the customer places an order for a design, i will design the same for him and want to send that file along with order completion email

        • You can create custom logic, for example name the files as design_[order_increment_id] and place it in a specific folder, so when sending mail, put custom code for file selection, or can store the order id and respective file name in a table or an XML file.

  3. jsch says:

    Thank you for this post.
    Works fine on 1.9.0.1

  4. shiks says:

    How can i attach multiple files in a order email using the above code. I would like to attach two pdf’s with order email.

    • Pragnesh says:

      You can make a zip file, it will be much easier to manage or you need to loop over the attachments.

    • ambaum2 says:

      I had the same use case (zip files would not do because end users get confused and works better on mobile). Its very simple to tweak this code for multi attachments. The problem with the code is that it will overwrite the previous attachment for every addAttachment method call.

      To fix:
      1. make _afile a multidimensional array $this->_afile[] = $tmp; in the addAttachment method (line 10 in example).
      2. Add a foreach loop in the send method inside the if statement and wrap the $_file stuff (lines 6-8 in the example)
      foreach($atInfo as $key => $value) {
      $_file = $mail->createAttachment($value[‘fileContents’]);
      $_file->type = ‘application/pdf';
      $_file->filename = $value[‘fileName’];
      }

      And that’s all. I haven’t tested much but see no problems. Thanks for the great example DWRoot saved me a ton of time!

  5. vetrivel says:

    hi i want to edit order mail in magento, once the user order any one products we will send one order mail, thanks for your order purchasing in (my site name), your order number is (xxxx).. where to edit these coding.. thanks in advance

  6. Vimal says:

    Hi,

    Folowing Url Is Great Help For Send An Attachment With Registartion Email

    http://www.webslike.com/Thread-How-To-Send-An-Attachment-With-Registartion-Email-In-Magento

  7. Frank says:

    Yippieh.
    Works like a charm now. Thanks!!!
    With this I’m nearer than ever to find a solution to my prob (have to add a unique
    pdf to each e-mail (NOT invoice or sth, could have used foomans ext then – i have to add a print preview of the ordered article (which is, who’d have thought, a postcard)). And i want it to only be attached to the copy of the mail which goes to the shop, not to the mail that goes to the customer. Please wish me the best of luck…

  8. Frank says:

    … on the other hand, it’s not in your downloadable code either… but if there is a function called that does not exist the whole call is useless? And it works for you, i suppose, otherwise you would’t have presented it here?

  9. Frank says:

    Hello, i once again went through everything and more and more i do believe that this:

    “Where is your implementation for the setOrderAttachments() and getOrderAttachments() functions you added in Template.php?”

    is the problem. Googling for “setOrderAttachments()” returns your page and 2 others of which one is a page where i can buy extensions. So it seems not to exist in Magento out of the box. So it must have been added (by you or some extension you maybe have installed and forgot about). May you have one last look at it please? Thanks!

  10. Frank says:

    Hey, no, nothing unclear with the code, i used your files, put them where they belong, let $file_name point to the same directory as you did, used a file test.txt within docs/, set permissions to 777 to be sure that’s not the prob but… Really no idea what goes wrong. Attaching email via backend works fine so adding attachments itself works. As i said, maybe someone messed with code in some other file(s) here, i have no clue. But – if you still have the patience or are keen on finding out what goes on: i’ve sent you an e-mail to your blog@decryptweb.com adress and added a short read me file there.

    I’ve sent the mail from my working e-mail address so don’t bother it differs from the one i entered in this form.

  11. Frank says:

    Hi, back on topic. Up to now i tried comparing my versions of the files with yours. Now i decided to replace my files with yours, created directory ‘docs’ in ‘var’ and even used a pdf named as yours (‘100000004.pdf’). Now on our server everything is an exact copy of your version. Still no attachments. I assume that some environmental differences exist or, well, i don’t know.
    Thanks again for source and your time spent on this, best regards, Frank.

    • Frank says:

      Oh, the pdf filename is from your dl-version, i now replaced it with the textfile ‘test.txt’ from the code above. Changed nothing. Thanks again.

  12. Frank says:

    Hi and thank you for the source. I am away from working on magento for about 3 weeks but this is important to me to get it done – so i will work on it and give feedback here. Thanks again.

  13. Frank says:

    Up to now still not working with 1.7.0.2.
    Prob seems to be
    $this->setOrderAttachments($attachments); and return $this->getOrderAttachments();

    Where are they defined? What do they (should they) do?

  14. Frank says:

    Hi there, me again, sorry for being kind of rude in my first statement – but there are so many ‘tutorials’ on the web leading nowhere… Yours didn’t seem like that so i wanted to make shure…

    I still have a problem with the inplementation and i think it comes from within ‘Template.php’. Within ‘public function getEmAttachments()’ i did:

    $fh = fopen(‘pdfs’ . DS . ‘mylog3.txt’, ‘w+’);
    fwrite($fh, ‘in public function getEmAttachments()’);
    fclose($fh);

    That works (file ‘mylog3.txt’ contains the string from fwrite).

    I’ve no idea about what might go wrong but what puzzles me is that i cannot find anywhere ‘$this->getOrderAttachments()’ from within ‘public function getEmAttachments()’.
    Where is it defined? Is it missing?

    Version used is 1.7.0.2.
    Thank you for anything that might help.
    Frank

    Within ‘if(!empty($atInfo))’ i did:

    $fh = fopen(‘pdfs’ . DS . ‘mylog4.txt’, ‘w+’);
    fwrite($fh, ‘in if(!empty($atInfo))’);
    fclose($fh);

    The file is not created nor is anything written to it.

  15. Frank says:

    Did anyone get this to work?
    The tutorial seems to be somewhat buggy, at least passages like “Copy the file found at app\code\core\Mage\Core\Model\Email\Template\Mailer.php to app\code\core\Mage\Core\Model\Email\Template\Mailer.php” do not make me very confident about the rest.

  16. Anthony says:

    Thx for your great tutorial! You should make the notes about model rewriting to avoid bad comments-).

    For example: function send() has Mage::getModel(‘core/email_template’) line. You should change that to Mage::getModel(‘your_module/email_template’) etc

  17. Ashish Khokhar says:

    $mailer = Mage::getModel(‘local/email_template_mailer’);
    if ($notifyCustomer) {
    $emailInfo = Mage::getModel(‘local/email_info’);
    print_r($emailInfo);
    I am getting error on this $email->info $emailInfo->addTo($this->getCustomerEmail(), $customerName);
    if ($copyTo && $copyMethod == ‘bcc’) {
    // Add bcc to customer email
    foreach ($copyTo as $email) {
    $emailInfo->addBcc($email);
    }
    }
    $mailer->addEmailInfo($emailInfo);

  18. Shiloh says:

    Hi, it doesn’t work for me too.

    Where is your implementation for the setOrderAttachments() and getOrderAttachments() functions you added in Template.php?

    Also, in Mailer.php send(), you forgot to change this line —->
    $emailTemplate = Mage::getModel(‘core/email_template’);
    to —->
    $emailTemplate = Mage::getModel(‘local/email_template’);

    • Shiloh says:

      ooops, my bad.. please ignore my comment for the Mailer.php…

      When I tried to purchase an item and got the “Main Store: New Order” Email notification, the test.txt file in var/docs directory is not attached.

      Can you help me check what’s wrong? I think your code needs a little bit of tweaking.

      Thanks.

      • Pragnesh says:

        Which version of Magento, are you using ? please check whether the path of the file is correct in your code and it exists and is readable

  19. Martijn says:

    Could you upload the complete class?
    Thanks in advance,

    Martijn

  20. Classical says:

    It’s not working!…

Leave a Reply

top