0

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? – Mohit Kumar Arora Sep 11 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 at 10:03
0

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" />
</config>

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

<?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.

0

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

https://github.com/DominicWatts/ContactAttachment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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