You upgraded your store to Magento 2.4.8, and suddenly the PDF invoices, CSV reports or catalog files that your custom module used to attach to emails are gone. The email is still sent, there is no error in var/log/exception.log, but the customer receives a plain HTML email without any attachment. Or worse, the code crashes with Class "Laminas\Mime\Mime" not found.
In this tutorial, we will learn how to add an attachment to an email in Magento 2 the way it works in Magento 2.4.8 and newer. We will build a tiny module that extends the core TransportBuilder with an addAttachment() method based on Symfony Mime, the library Magento now uses to build emails. The same module can send any file: a PDF invoice, a CSV export, an image, and so on.
If you are still on an older version, my guide on how to upgrade Magento 2 to the latest version explains the upgrade itself. This article focuses on fixing email attachments after you are on 2.4.8.
Contents
Why email attachments stopped working in Magento 2.4.8
Before 2.4.8, Magento built emails with laminas/laminas-mail and laminas/laminas-mime. Most attachment tutorials and extensions created an extra MIME part for the file and passed it to the message together with the HTML body.
Magento 2.4.8 replaced both Laminas packages. According to the Adobe Commerce 2.4.8 release notes, laminas/laminas-mail and laminas/laminas-mime were “replaced with alternative packages”. In the core code, the replacement is symfony/mailer and symfony/mime. You can confirm it on your own server:
php bin/magento --version grep -E '"symfony/(mailer|mime)"' composer.json grep -c '"name": "laminas/laminas-mime"' composer.lock
This change breaks old attachment code in two ways:
- Code that uses Laminas classes directly (
Laminas\Mime\Part,Laminas\Mime\Mime,Laminas\Mime\Message) fails with a “class not found” fatal error, because the package is no longer installed. - Code that uses Magento’s own mail factories still runs, but the attachment disappears silently. In 2.4.8,
Magento\Framework\Mail\MimeMessageloops over the parts you give it and keeps only the first text part (the HTML or plain-text body). Any extra part, like your PDF, is ignored.
Here is the typical pre-2.4.8 pattern that now loses the attachment:
// Typical pre-2.4.8 code: add the file as an extra MIME part
$attachmentPart = $this->mimePartInterfaceFactory->create([
'content' => $content,
'type' => 'application/pdf',
'fileName' => 'invoice.pdf',
'disposition' => MimeInterface::DISPOSITION_ATTACHMENT,
'encoding' => MimeInterface::ENCODING_BASE64,
]);
$body = $this->mimeMessageInterfaceFactory->create([
'parts' => [$htmlPart, $attachmentPart], // in 2.4.8 only the HTML part survives
]);
The fix is to let Magento build the message as usual, then take the underlying Symfony message and replace its body with a multipart/mixed part that contains the original body plus your files. That’s exactly what we will do now.
Step 1: Create the module skeleton
We will create a module called Magentip_EmailAttachment. If you have never created a module before, read my tutorial on how to create a custom Helloworld module in Magento 2 first. Here is the final structure:
app/code/Magentip/EmailAttachment/
├── registration.php
├── etc/
│ ├── module.xml
│ └── email_templates.xml
├── Model/
│ ├── Mail/TransportBuilder.php
│ └── AttachmentMailer.php
└── view/frontend/email/
└── document_attachment.html
Create registration.php:
<?php
// app/code/Magentip/EmailAttachment/registration.php
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(
ComponentRegistrar::MODULE,
'Magentip_EmailAttachment',
__DIR__
);
Then create etc/module.xml:
<?xml version="1.0"?>
<!-- app/code/Magentip/EmailAttachment/etc/module.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Magentip_EmailAttachment">
<sequence>
<module name="Magento_Email"/>
</sequence>
</module>
</config>
Step 2: Extend the TransportBuilder with addAttachment()
This is the heart of the solution. Our class extends Magento\Framework\Mail\Template\TransportBuilder, collects the files in an array of Symfony DataPart objects, and wraps the body after the core prepareMessage() has built the email.
<?php
// app/code/Magentip/EmailAttachment/Model/Mail/TransportBuilder.php
declare(strict_types=1);
namespace Magentip\EmailAttachment\Model\Mail;
use Magento\Framework\Mail\EmailMessage;
use Magento\Framework\Mail\Template\TransportBuilder as CoreTransportBuilder;
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\Multipart\MixedPart;
class TransportBuilder extends CoreTransportBuilder
{
/**
* @var DataPart[]
*/
private array $attachments = [];
/**
* Add a file to the next email built by this builder
*/
public function addAttachment(
string $content,
string $fileName,
string $mimeType = 'application/octet-stream'
): self {
$this->attachments[] = new DataPart($content, $fileName, $mimeType);
return $this;
}
/**
* Build the message as usual, then wrap the body and the files in multipart/mixed
*/
protected function prepareMessage()
{
parent::prepareMessage();
if ($this->attachments && $this->message instanceof EmailMessage) {
$symfonyMessage = $this->message->getSymfonyMessage();
$symfonyMessage->setBody(
new MixedPart($symfonyMessage->getBody(), ...$this->attachments)
);
}
return $this;
}
/**
* Clear the files after each email, like the core clears template data
*/
protected function reset()
{
$this->attachments = [];
return parent::reset();
}
}
A few notes about this code:
getSymfonyMessage()exists onMagento\Framework\Mail\EmailMessage, the class Magento 2.4.8 uses for template emails, which is why we check the type withinstanceof.- The core transport in 2.4.8 sends exactly this Symfony message, so whatever we put in the body is what the customer receives.
- We clear the attachments in
reset(). The core callsreset()after everygetTransport(), so a file never “leaks” into the next email sent with the same builder instance. - We don’t use a
preferenceindi.xml. Replacing the coreTransportBuilderglobally would affect every email in the store and can conflict with SMTP extensions. Instead, we inject our class only where we need attachments.
Step 3: Add an email template
Every template email in Magento needs a template ID. Declare one in etc/email_templates.xml:
<?xml version="1.0"?>
<!-- app/code/Magentip/EmailAttachment/etc/email_templates.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Email:etc/email_templates.xsd">
<template id="magentip_document_attachment"
label="Magentip: Document attachment"
file="document_attachment.html"
type="html"
module="Magentip_EmailAttachment"
area="frontend"/>
</config>
Then create the template file view/frontend/email/document_attachment.html:
<!--@subject {{trans "Your document from %store_name" store_name=$store.frontend_name}} @-->
<!--@vars {
"var customer_name":"Customer name"
} @-->
{{template config_path="design/email/header_template"}}
<p>{{trans "Hello %name," name=$customer_name}}</p>
<p>{{trans "Please find your document attached to this email."}}</p>
{{template config_path="design/email/footer_template"}}
Because the template is registered, store admins can also customize it later in Marketing > Communications > Email Templates > Add New Template by loading the “Magentip: Document attachment” template.
Step 4: Attach the file and send the email
Now create a small service that reads a file from the var/ directory and sends it. Notice that we inject our TransportBuilder, not the core one:
<?php
// app/code/Magentip/EmailAttachment/Model/AttachmentMailer.php
declare(strict_types=1);
namespace Magentip\EmailAttachment\Model;
use Magento\Framework\App\Area;
use Magento\Framework\Filesystem;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magentip\EmailAttachment\Model\Mail\TransportBuilder;
class AttachmentMailer
{
public function __construct(
private readonly TransportBuilder $transportBuilder,
private readonly StateInterface $inlineTranslation,
private readonly StoreManagerInterface $storeManager,
private readonly Filesystem $filesystem
) {
}
/**
* Send a file from var/ (e.g. var/export/report.pdf) to a customer
*/
public function send(string $email, string $name, string $relativePath): void
{
$store = $this->storeManager->getStore();
$varDir = $this->filesystem->getDirectoryRead(DirectoryList::VAR_DIR);
$content = $varDir->readFile($relativePath);
$this->inlineTranslation->suspend();
try {
$transport = $this->transportBuilder
->setTemplateIdentifier('magentip_document_attachment')
->setTemplateOptions(['area' => Area::AREA_FRONTEND, 'store' => $store->getId()])
->setTemplateVars(['customer_name' => $name, 'store' => $store])
->setFromByScope('general', $store->getId())
->addTo($email, $name)
->addAttachment($content, basename($relativePath), 'application/pdf')
->getTransport();
$transport->sendMessage();
} finally {
$this->inlineTranslation->resume();
}
}
}
You can call AttachmentMailer::send() from a controller, an observer, a cron job or a CLI command. For example, send('john@example.com', 'John Doe', 'export/report.pdf') sends var/export/report.pdf as report.pdf.
To attach a PDF invoice generated by Magento instead of a file on disk, use the core invoice PDF model and pass the rendered content:
// Inject \Magento\Sales\Model\Order\Pdf\Invoice $invoicePdf in the constructor, then:
$pdf = $this->invoicePdf->getPdf([$invoice]);
$this->transportBuilder->addAttachment(
$pdf->render(),
'invoice-' . $invoice->getIncrementId() . '.pdf',
'application/pdf'
);
Always pass the correct MIME type as the third argument (application/pdf, text/csv, image/png…), otherwise some mail clients show the attachment as an unknown file.
Step 5: Enable the module and test
Run the usual commands from the Magento root folder:
php bin/magento module:enable Magentip_EmailAttachment php bin/magento setup:upgrade php bin/magento setup:di:compile php bin/magento cache:flush
Trigger your code and check the inbox. During development, I recommend catching emails with a local tool such as Mailpit or MailHog, so you can open the raw source. A correct email looks like this:
Content-Type: multipart/mixed; boundary=588TourU --588TourU Content-Type: text/html; charset=utf-8 Content-Transfer-Encoding: quoted-printable <p>Hello John Doe,</p> ... --588TourU Content-Type: application/pdf; name=report.pdf Content-Transfer-Encoding: base64 Content-Disposition: attachment; name=report.pdf; filename=report.pdf JVBERi0xLjQKJ... --588TourU--
If you see multipart/mixed with your HTML part first and the file as a second part with Content-Disposition: attachment, everything works.
Common errors
The email arrives but without the attachment. You are still using the old pattern (extra part passed to MimeMessageInterfaceFactory), or your class is not the one being injected. Run setup:di:compile again and check that the constructor type-hints Magentip\EmailAttachment\Model\Mail\TransportBuilder. Adding a log line in prepareMessage() helps here; see my tutorial on how to write logs to a custom file in Magento 2.
Error: Class “Laminas\Mime\Mime” not found. A custom module or an old extension still references Laminas classes. Replace constants like Laminas\Mime\Mime::DISPOSITION_ATTACHMENT with Magento\Framework\Mail\MimeInterface::DISPOSITION_ATTACHMENT, and attachment logic with the addAttachment() method above. For third-party extensions, update to a version marked compatible with 2.4.8. Don’t add laminas/laminas-mime back with Composer: Magento no longer uses it to send mail, so it won’t bring the attachment back.
Call to undefined method addAttachment(). You injected the core Magento\Framework\Mail\Template\TransportBuilder instead of the extended class. Check the use statement in your service.
The attachment is corrupted or 0 KB. Make sure you pass the raw file content (for example $pdf->render() or readFile()), not a file path and not a base64 string. Symfony Mime encodes the file to base64 for you.
Emails are not sent at all after the upgrade. That’s a different problem: Magento 2.4.8 also changed SMTP handling, and some TLS setups need the fix from GitHub issue #39947 (included in 2.4.8-p2 and 2.4.9). Check var/log/exception.log and your SMTP settings in Stores > Configuration > Advanced > System > Mail Sending Settings.
Wrapping up
Email attachments broke in Magento 2.4.8 because Laminas Mail and Laminas Mime were replaced by Symfony Mailer and Symfony Mime, and the old “extra MIME part” trick is now silently ignored. The fix is a small TransportBuilder subclass that wraps the email body and your files in a Symfony MixedPart, plus an email template and a service that calls addAttachment(). It works for PDF invoices, CSV exports or any other file, and it doesn’t touch the core emails of your store. For more Magento CLI commands you may need while testing, keep my Magento 2 command list cheat sheet close.
Did this fix the attachments in your 2.4.8 store, or are you stuck with a specific extension? Leave a comment below and let me know.





