How to send the simple mail with CSV attachment file in Magento 2.
Please help me to solve out this Question.
Thanks in Advanced.
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityHow to send the simple mail with CSV attachment file in Magento 2.
Please help me to solve out this Question.
Thanks in Advanced.
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.
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