Reading list Switch to dark mode

    Magento 2 – Adding attachment in order invoice email

    Updated 1 May 2023

    Sometimes, we need to attach a file with the order invoice email, so here are the steps to achieve the same.

    first of all create TransportBuilder class in app/code/Vendor/Module /Mail/Template/ TransportBuilder.php

    <?php
    
    namespace Vendor\Module\Mail\Template;
    
    class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder
    {
       /**
        * addAttachment
        *
        * @param mixed $body
        * @param string $filename
        * @param mixed $mimeType
        * @param mixed $disposition
        * @param mixed $encoding
        * @return object
        */
        public function addAttachment(
            $body,
            $filename = null,
            $mimeType = \Zend_Mime::TYPE_OCTETSTREAM,
            $disposition = \Zend_Mime::DISPOSITION_ATTACHMENT,
            $encoding = \Zend_Mime::ENCODING_BASE64
        ) {
            $attachmentPart = new \Zend\Mime\Part();
            $attachmentPart->setContent($body)
                ->setType($mimeType)
                ->setFileName($filename)
                ->setEncoding($encoding)
                ->setDisposition($disposition);
    
            return $attachmentPart;
        }
    }

    Now, create the SenderBuilder class to add attachment files which is extend to core class \Magento\Sales\Model \Order\Email\ SenderBuilder. You can add image/pdf/docx/calender etc. files with email.

    Add the SenderBuilder file in app/code/Vendor/Module/Model/Sales/Order/Email/SenderBuilder.php.

    <?php
    
    namespace Vendor\Module\Model\Sales\Order\Email;
    
    use Magento\Framework\Mail\Template\TransportBuilder;
    use Magento\Framework\Mail\Template\TransportBuilderByStore;
    use Magento\Sales\Model\Order\Email\Container\IdentityInterface;
    use Magento\Sales\Model\Order\Email\Container\Template;
    
    /**
     * Email sender builder for attachments
     */
    class SenderBuilder extends \Magento\Sales\Model\Order\Email\SenderBuilder
    {
        /**
         * @param Template $templateContainer
         * @param IdentityInterface $identityContainer
         * @param TransportBuilder $transportBuilder
         * @param TransportBuilderByStore $transportBuilderByStore
         * @param \Magento\Framework\Filesystem\Driver\File $reader
         */
        public function __construct(
            Template $templateContainer,
            IdentityInterface $identityContainer,
            TransportBuilder $transportBuilder,
            TransportBuilderByStore $transportBuilderByStore = null,
            \Vendor\Module\Helper\Data $helper,
            \Magento\Framework\Filesystem\Driver\File $reader
        ) {
            parent::__construct(
                $templateContainer,
                $identityContainer,
                $transportBuilder
            );
            $this->helper = $helper;
            $this->reader = $reader;
        }
    
        /**
         * Prepare and send email message
         *
         * @return void
         */
        public function send()
        {
            $this->configureEmailTemplate();
    
            $this->transportBuilder->addTo(
                $this->identityContainer->getCustomerEmail(),
                $this->identityContainer->getCustomerName()
            );
    
            $copyTo = $this->identityContainer->getEmailCopyTo();
    
            if (!empty($copyTo) && $this->identityContainer->getCopyMethod() == 'bcc') {
                foreach ($copyTo as $email) {
                    $this->transportBuilder->addBcc($email);
                }
            }
    
            /* to attach events in invoice email */
            $templateVars = $this->templateContainer->getTemplateVars();
            $transport = $this->transportBuilder->getTransport();
    
            if (!empty($templateVars['order'])) {
                $order = $templateVars['order'];
                foreach ($order->getAllItems() as $item) {
                    $data = $this->helper->createPdfFile($item, $order->getId());
                    if (!empty($data) && !empty($data['filename']) && !empty($data['pdfFile'])) {
                        // adds attachment in mail
                        $attachmentPart = $this->transportBuilder->addAttachment(
                            $this->reader->fileGetContents($data['pdfFile']),
                            $data['filename'],
                            'application/pdf'
                        );
    
                        $message = $transport->getMessage();
                        $body = \Zend\Mail\Message::fromString($message->getRawMessage())->getBody();
                        $body = \Zend_Mime_Decode::decodeQuotedPrintable($body);
                        $html = '';
    
                        if ($body instanceof \Zend\Mime\Message) {
                            $html = $body->generateMessage(\Zend\Mail\Headers::EOL);
                        } elseif ($body instanceof \Magento\Framework\Mail\MimeMessage) {
                            $html = (string) $body->getMessage();
                        } elseif ($body instanceof \Magento\Framework\Mail\EmailMessage) {
                            $html = (string) $body->getBodyText();
                        } else {
                            $html = (string) $body;
                        }
    
                        $htmlPart = new \Zend\Mime\Part($html);
                        $htmlPart->setCharset('utf-8');
                        $htmlPart->setEncoding(\Zend_Mime::ENCODING_QUOTEDPRINTABLE);
                        $htmlPart->setDisposition(\Zend_Mime::DISPOSITION_INLINE);
                        $htmlPart->setType(\Zend_Mime::TYPE_HTML);
                        $parts = [$htmlPart, $attachmentPart];
    
                        $bodyPart = new \Zend\Mime\Message();
                        $bodyPart->setParts($parts);
                        $message->setBody($bodyPart);
                    }
                }
            }
    
            $transport->sendMessage();
        }
    }

    Finally, add the following code in app/code/Vendor/Module/etc/di.xml to use TransportBuilder class of your module and you are good to go.

    Start your headless eCommerce
    now.
    Find out More
    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
      <preference for="\Magento\Framework\Mail\Template\TransportBuilder" type="Vendor\Module\Model\Mail\TransportBuilder" />
    </config>
    
    Moreover, you can also view our module <a href="https://store.webkul.com/magento2-order-attachment.html">Magento 2 Order attachment</a>.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    4 comments

  • Kaleem
    • Ritika Singh (Moderator)
  • Faisal
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home