Menu Close
    Searching for an experienced eCommerce & Marketplace Development Company ?

    How to attach Pdf file in Magento 2 Email

    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.

    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.

    . . .
    Discuss on Helpdesk

    Leave a Comment

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


    2 comments

  • Rajan Soni
    sendMessage is not working
    Uncaught Error: Call to undefined method [NAMESPACE][MODULE]ModelMailTransportBuilder::sendMessage()
  • Gavino Covone
    Hello,
    sending e-mail with an attachment is working properly.

    But the email arrives in spam. How to do to not let it get to spam?

    Thank you.

  • Back to Top