How to Programmatically Attach PDF File in Magento 2 Email
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.
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 attach a PDF file in Magento 2 Email!
Magento 2 uses the lib/internal/Magento/Framework/Mail/Template/TransportBuilder class to send Emails, which doesn’t support file attachments yet. However, as the TransportBuilder Class uses Message class inherited from the \Zend_Mail, we can add Email attachments programmatically.
Here’s the solution for the same.
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 Magento 2 Email Attachments extension that allows attaching important order documents, terms, and conditions, policy documents, spreadsheets, offer images, pamphlets, etc. in sales emails.
Method to Programmatically Attach PDF File in Magento 2 Email:
- Create your TransportBuilder class, Vendor/Extension/Model/Mail/TransportBuilder.php
1234567891011121314151617<?phpnamespace Vendor\Extension\Model\Mail;class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder{public function addAttachment($pdfString){$this->message->createAttachment($pdfString,'application/pdf',\Zend_Mime::DISPOSITION_ATTACHMENT,\Zend_Mime::ENCODING_BASE64,'attatched.pdf');return $this;}} - Here I have created sample Email Sending Helper, Vendor/Extension/Helper/Data.php
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263<?phpnamespace Vendor\Extension\Helper;use Magento\Customer\Model\Session;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;public function __construct(\Magento\Framework\App\Helper\Context $context,\Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,\Vendor\Extension\Model\Mail\TransportBuilder $transportBuilder,\Magento\Store\Model\StoreManagerInterface $storeManager){$this->_objectManager = $objectManager;parent::__construct($context);$this->_inlineTranslation = $inlineTranslation;$this->_transportBuilder = $transportBuilder;$this->_storeManager = $storeManager;}public function generateTemplate(){$pdfFile = 'pdf_file_path/email.pdf';$emailTemplateVariables['message'] = 'This is a test message by meetanshi.';//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' => 'Meetanshi',])->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;}}
Implement the above code to programmatically attach a PDF file in Magento 2 Email and save yourself from the tedious repetitive tasks!
Any doubts about the method are welcome in the comments section below.
Happy Emailing
Attach important documents such as policy information, T&C, and more in your sales emails.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
6 Comments
How to add multiple type of file in email at once ???
Hello Bhargav,
If the this->message->createAttachment() is working in your store then
call the below methods
->addAttachment(file_get_contents($pdfFile1)
->addAttachment(file_get_contents($pdfFile2)
Thank You
What will be the pdf file path?
Hello Mohit,
In addAttachment($pdfString) function, you have to pass the data of pdf. Not a path.
You have to set the name of pdf instead of “attached.pdf”.
Thank you.
Hellom this just c’ant work cause magento 2 dont define createAttachement in the class of transportBuilder
Hello,
Please refer here for the solution: https://meetanshi.com/blog/add-attachments-with-email-in-magento-2-3-x/
Thank you.