{"id":287,"date":"2019-01-18T11:12:13","date_gmt":"2019-01-18T11:12:13","guid":{"rendered":"https:\/\/meetanshi.com\/blog\/2019\/01\/18\/programmatically-attach-pdf-file-in-magento-2-email\/"},"modified":"2025-05-22T17:08:34","modified_gmt":"2025-05-22T11:38:34","slug":"programmatically-attach-pdf-file-in-magento-2-email","status":"publish","type":"post","link":"https:\/\/meetanshi.com\/blog\/programmatically-attach-pdf-file-in-magento-2-email\/","title":{"rendered":"How to Programmatically Attach PDF File in Magento 2 Email"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Email Attachments are an easy way to send files without any barriers of geographical locations, security breaches, or cost. PDF files are usually preferred as they are uneditable, password-protected, small-sized, and easily accessible.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For Magento 2 stores, generally, Emails are sent for various purposes such as invoice, billing, coupon codes, etc. that require to attach PDF files. Manually attaching files for these tasks is not feasible. Instead, programmatically&nbsp;attach a PDF file in Magento 2 Email!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Magento 2 uses the <strong>lib\/internal\/Magento\/Framework\/Mail\/Template\/TransportBuilder<\/strong> class to send Emails, which doesn\u2019t support file attachments yet.\u200b\u200b\u200b\u200b\u200b\u200b\u200b&nbsp;However, as the&nbsp;<strong>TransportBuilder<\/strong>&nbsp;Class uses&nbsp;<strong>Message<\/strong>&nbsp;class inherited from the<strong>&nbsp;Zend_Mail<\/strong>, we can add Email attachments programmatically.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s the solution for the same.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Please note that the below <strong>solution is compatible till <a href=\"https:\/\/meetanshi.com\/blog\/magento-2-3-5-release\/\" target=\"_blank\" rel=\"noreferrer noopener\">Magento 2.3.5<\/a> version only<\/strong>. If your store is running on versions above Magento 2.3.5, you may opt for <strong><a href=\"https:\/\/meetanshi.com\/magento-2-email-attachments.html\" target=\"_blank\" rel=\"noreferrer noopener\">Magento 2 Email Attachments<\/a><\/strong> extension that allows attaching important order documents, terms, and conditions, policy documents, spreadsheets, offer images, pamphlets, etc. in sales emails.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Method to Programmatically Attach PDF File in Magento 2 Email:<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">1. Create your TransportBuilder class, Vendor\/Extension\/Model\/Mail\/TransportBuilder.php<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\nnamespace Vendor\\Extension\\Model\\Mail;\n \nclass TransportBuilder extends \\Magento\\Framework\\Mail\\Template\\TransportBuilder\n{\n    public function addAttachment($pdfString)\n    {\n        $this->message->createAttachment(\n            $pdfString,\n            'application\/pdf',\n            \\Zend_Mime::DISPOSITION_ATTACHMENT,\n            \\Zend_Mime::ENCODING_BASE64,\n            'attatched.pdf'\n        );\n        return $this;\n    }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;2. Here I have created sample Email Sending Helper,&nbsp;<strong><strong>Vendor\/Extension\/Helper\/Data.php<\/strong><\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\nnamespace Vendor\\Extension\\Helper;\n \nuse Magento\\Customer\\Model\\Session;\n \nclass Data extends \\Magento\\Framework\\App\\Helper\\AbstractHelper\n{\n    const XML_PATH_EMAIL_DEMO = 'emaildemo\/email\/email_demo_template';\n    protected $_inlineTranslation;\n    protected $_transportBuilder;\n    protected $_template;\n    protected $_storeManager;\n \n    public function __construct(\n        \\Magento\\Framework\\App\\Helper\\Context $context,\n        \\Magento\\Framework\\Translate\\Inline\\StateInterface $inlineTranslation,\n        \\Vendor\\Extension\\Model\\Mail\\TransportBuilder $transportBuilder,\n        \\Magento\\Store\\Model\\StoreManagerInterface $storeManager\n    ) \n    {\n        $this->_objectManager = $objectManager;\n        parent::__construct($context);\n        $this->_inlineTranslation = $inlineTranslation;\n        $this->_transportBuilder = $transportBuilder;\n        $this->_storeManager = $storeManager;\n    }\n \n    public function generateTemplate()\n    {\n        $pdfFile = 'pdf_file_path\/email.pdf';\n \n        $emailTemplateVariables['message'] = 'This is a test message by meetanshi.';\n        \/\/load your email tempate\n        $this->_template  = $this->scopeConfig->getValue(\n            self::XML_PATH_EMAIL_DEMO,\n            \\Magento\\Store\\Model\\ScopeInterface::SCOPE_STORE,\n            $this->_storeManager->getStore()->getStoreId()\n        );\n        $this->_inlineTranslation->suspend();\n \n        $this->_transportBuilder->setTemplateIdentifier($this->_template)\n                ->setTemplateOptions(\n                    [\n                        'area' => \\Magento\\Framework\\App\\Area::AREA_FRONTEND,\n                        'store' => $this->_storeManager->getStore()->getId(),\n                    ]\n                )\n                ->setTemplateVars($emailTemplateVariables)\n                ->setFrom([\n                    'name' => 'Meetanshi',\n                    'email' => 'meetanshi@meetanshi.com',\n                ])\n                ->addTo('yourname@gmail.com', 'Your Name')\n                ->addAttachment(file_get_contents($pdfFile)); \/\/Attachment goes here.\n \n        try {\n            $transport = $this->_transportBuilder->getTransport();\n            $transport->sendMessage();\n            $this->_inlineTranslation->resume();\n        } catch (\\Exception $e) {\n            echo $e->getMessage(); die;\n        }\n    }<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Implement the above code to programmatically attach a PDF file in Magento 2 Email and save yourself from the tedious repetitive tasks!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Happy Emailing<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Email Attachments are an easy way to send files without any barriers of geographical locations, security breaches, or cost. PDF files are usually preferred as&#8230;<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[34],"tags":[],"class_list":["post-287","post","type-post","status-publish","format-standard","hentry","category-magento"],"acf":[],"_links":{"self":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/287","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/comments?post=287"}],"version-history":[{"count":4,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/287\/revisions"}],"predecessor-version":[{"id":15527,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/287\/revisions\/15527"}],"wp:attachment":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media?parent=287"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/categories?post=287"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/tags?post=287"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}