Reading list Switch to dark mode

    How to attach Pdf file in Magento 2 Email

    Updated 23 February 2024

    Here we learn, how to send attachment in magento 2 email programmatically. I have attached pdf file here.

    Magento 2 uses the lib/internal/Magento/Framework/Mail/Template/TransportBuilder class to send mail, which doesn’t support attachment yet.

    TransportBuilder class uses the lib/internal/Magento/Framework/Mail/Message.php to prepare the email message.

    Here we can observe that Message class extends \Zend_Mail so we can add attachment functionality in TransportBuilder Class.

    Please note that the below solution is compatible till Magento 2.3.5 version only. If your store is running on versions above Magento 2.3.5, you may opt for Order Attachments for Magento 2 extension in which the customers can upload file attachments with the order.

    Start your headless eCommerce
    now.
    Find out More

    1. create your TransportBuilder class, Webkul/EmailDemo/Model/Mail/TransportBuilder.php

    <?php
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @package   Webkul_EmailDemo
     * @author    Webkul
     * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
     */
    
    namespace Webkul\EmailDemo\Model\Mail;
    
    class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder
    {
        /**
         * @param Api\AttachmentInterface $attachment
         */
        public function addAttachment($pdfString)
        {
            $this->message->createAttachment(
                $pdfString,
                'application/pdf',
                \Zend_Mime::DISPOSITION_ATTACHMENT,
                \Zend_Mime::ENCODING_BASE64,
                'attatched.pdf'
            );
            return $this;
        }
    }

    2. Here i have created sample Email Sending Helper, Webkul/EmailDemo/Helper/Data.php

    <?php
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @package   Webkul_EmailDemo
     * @author    Webkul
     * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
     */
    namespace Webkul\EmailDemo\Helper;
    
    use Magento\Customer\Model\Session;
    
    /**
     * Webkul EmailDemo Helper. you can write email sending code where ever you want.
     */
    class Data extends \Magento\Framework\App\Helper\AbstractHelper
    {
        const XML_PATH_EMAIL_DEMO = 'emaildemo/email/email_demo_template';
    
        protected $_inlineTranslation;
    
        protected $_transportBuilder;
    
        protected $_template;
    
        protected $_storeManager;
    
        /**
         * @param Magento\Framework\App\Helper\Context              $context
         * @param Magento\Framework\Translate\Inline\StateInterface $inlineTranslation
         * @param Magento\Framework\Mail\Template\TransportBuilder  $transportBuilder
         * @param Magento\Store\Model\StoreManagerInterface         $storeManager
         */
        public function __construct(
            \Magento\Framework\App\Helper\Context $context,
            \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
            \Webkul\EmailDemo\Model\Mail\TransportBuilder $transportBuilder,
            \Magento\Store\Model\StoreManagerInterface $storeManager
        ) 
        {
            $this->_objectManager = $objectManager;
            parent::__construct($context);
            $this->_inlineTranslation = $inlineTranslation;
            $this->_transportBuilder = $transportBuilder;
            $this->_storeManager = $storeManager;
        }
    
        /**
         * [generateTemplate description].
         *
         * @param Mixed $emailTemplateVariables
         * @param Mixed $senderInfo
         * @param Mixed $receiverInfo
         */
        public function generateTemplate()
        {
            $pdfFile = 'pdf_file_path/email.pdf';
    
            $emailTemplateVariables['message'] = 'This is a test message.';
            //load your email tempate
            $this->_template  = $this->scopeConfig->getValue(
                self::XML_PATH_EMAIL_DEMO,
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
                $this->_storeManager->getStore()->getStoreId()
            );
            $this->_inlineTranslation->suspend();
    
            $this->_transportBuilder->setTemplateIdentifier($this->_template)
                    ->setTemplateOptions(
                        [
                            'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                            'store' => $this->_storeManager->getStore()->getId(),
                        ]
                    )
                    ->setTemplateVars($emailTemplateVariables)
                    ->setFrom([
                        'name' => 'MyName',
                        'email' => '[email protected]',
                    ])
                    ->addTo('[email protected]', 'Your Name')
                    ->addAttachment(file_get_contents($pdfFile)); //Attachment goes here.
    
            try {
                $transport = $this->_transportBuilder->getTransport();
                $transport->sendMessage();
                $this->_inlineTranslation->resume();
            } catch (\Exception $e) {
                echo $e->getMessage(); die;
            }
        }
    }

    That’s it.

    . . .

    Leave a Comment

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


    2 comments

  • Rajan Soni
  • Gavino Covone
  • Back to Top

    Message Sent!

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

    Back to Home