Magento2 Email Attachment – How to Send Email with Attachment in Magento 2

attachmentemailmagento2

How to send email with a file attachment.

Best Answer

M2 does not come with out of the box however it is a feature built into the zend framework. Here is a good reference how to add this functionality into magento: https://blog.bitexpert.de/blog/sending-mails-with-attachments-in-magento-2/

In case link goes dead, create the following

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

then add to etc/di.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="\Magento\Framework\Mail\Template\TransportBuilder"
                type="\Your\CustomModule\Magento\Mail\Template\TransportBuilder" />
</config>

Now you can use addAttachment() throughout your site.

Related Topic