How to send the simple mail with CSV attachment file in Magento 2.

Please help me to solve out this Question.

Thanks in Advanced.

  • did you tried the solution posted by me? Sep 11, 2019 at 9:49
  • @MohitKumarArora, to be honest, I don't know how to send an email with CSV File and also I am confused with your code in where should I place the receiver email.
    – AKM
    Sep 11, 2019 at 10:03

2 Answers 2


First of all, Magento (at the time of writing, I am using Magento version 2.2.7) does not provide the functionality to add an attachment in the email.

To add an attachment programmatically in the email, first, you need to override \Magento\Framework\Mail\Template\TransportBuilder class.

Step 1: app/code/[Namespace]/[Module]/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="\[Namespace]\[Module]\Mail\Template\TransportBuilder" />

Step 2: app/code/[Namespace]/[Module]/Mail/Template/TransportBuilder.php


namespace Stream\EmailPrintableCsv\Mail\Template;

class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder {

    public function addAttachment(
    $filePath, $filename = null, $mimeType = \Zend_Mime::TYPE_OCTETSTREAM, $disposition = \Zend_Mime::DISPOSITION_ATTACHMENT, $encoding = \Zend_Mime::ENCODING_BASE64
    ) {
        if (file_exists($filePath)) {
            $body = file_get_contents($filePath);
            $this->message->createAttachment($body, $mimeType, $disposition, $encoding, $filename);
        return $this;


Now, you can call addAttachment() function while sending an email.

Note: addAttachment function requires 2 parameters: filePath and fileName.


I wrote an extension to allow you to attach a file to the contact form

Take a look at the controller

You might find it helpful


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.