🔥 Just Launched! Werra Premium Template for HyväSee it in Action

How to Programmatically Attach PDF File in Magento 2 Email

By Sanjay JethvaUpdated on May 22, 2025 2 min read

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:

1. Create your TransportBuilder class, Vendor/Extension/Model/Mail/TransportBuilder.php

<?php
namespace 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;
    }
}

 2. Here I have created sample Email Sending Helper, Vendor/Extension/Helper/Data.php

<?php
namespace 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',
                    '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;
        }
    }

Implement the above code to programmatically attach a PDF file in Magento 2 Email and save yourself from the tedious repetitive tasks!

Happy Emailing

Sanjay Jethva Full Image
Article bySanjay 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.