Skip to main content

Sending mails with attachments in Magento 2

This blog post might be outdated!
This blog post was published more than one year ago and might be outdated!
· One min read
Florian Horn

The Magento 2 Transport Builder, responsible for preparing a mail message, wraps the mail component of the Zend Framework. Unfortunatly it is missing a method to add attachments. I submitted a Pull Request to Magento 2 to fix the issue but for now we need a work-a-round in our project. First we extend the Magento 2 Transport Builder like this:

<?php
namespace bitExpert\Magento\Mail\Template;

class TransportBuilder
extends \Magento\Framework\Mail\Template\TransportBuilder
{
public function addAttachment(
$body,
$mimeType = Zend_Mime::TYPE_OCTETSTREAM,
$disposition = Zend_Mime::DISPOSITION_ATTACHMENT,
$encoding = Zend_Mime::ENCODING_BASE64,
$filename = null
) {
$this->message->createAttachment($body, $mimeType, $disposition,
$encoding, $filename);
return $this;
}
}

To make sure Magento 2 will pick our implementation of the TransportBuilder we need to extend the configuration to add a preference setting for the \Magento\Framework\Mail\Template\TransportBuilder type:

<preference for="\Magento\Framework\Mail\Template\TransportBuilder"
type="\bitExpert\Magento\Mail\Template\TransportBuilder" />