1

I have created custom module for quotation in Magento2.3.0.

Module is working as per requirement but I want to send an attachment also in the email which is not working.

I am sending email from controller. can anyone suggest how can I send the attachment in the email?

My controller code is:

<?php

namespace Vendor\CustomForm\Controller\Index;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\ResultFactory; 


class Index extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Framework\Mail\Template\TransportBuilder
     */
    protected $_transportBuilder;

    /**
     * @var \Magento\Framework\Translate\Inline\StateInterface
     */
    protected $inlineTranslation;

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;
    /**
     * @var \Magento\Framework\Escaper
     */
    protected $_escaper;

    protected $_filesystem;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Filesystem $fileSystem,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Escaper $escaper
    ) {
        $this->_transportBuilder = $transportBuilder;
        $this->inlineTranslation = $inlineTranslation;
        $this->scopeConfig = $scopeConfig;
        $this->storeManager = $storeManager;
        $this->_escaper = $escaper;
        $this->_filesystem = $fileSystem;
        parent::__construct($context);
    }

    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $storeManager=$objectManager->create('\Magento\Store\Model\StoreManagerInterface');
        $baseUrl = $storeManager->getStore()->getBaseUrl();
        $baseMediaUrl = $objectManager->get('Magento\Store\Model\StoreManagerInterface')
                    ->getStore()
                    ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

        $post = $this->getRequest()->getPost();
        $scopeConfig = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface');

        $emailAdmin = $scopeConfig->getValue('trans_email/ident_custom1/email', \Magento\Store\Model\ScopeInterface::SCOPE_STORE );
        $nameAdmin = $scopeConfig->getValue('trans_email/ident_custom1/name', \Magento\Store\Model\ScopeInterface::SCOPE_STORE );

        if (!$post) {
            $this->_redirect('*/*/');
            return;
        }

        $model = $objectManager->create('Vendor\CustomForm\Model\Customform');
        $imagePath = '';

        if(1)
        {
            $result = '';

            $profileImage = $this->getRequest()->getFiles('image');
            $fileName = ($profileImage && array_key_exists('name', $profileImage)) ? $profileImage['name'] : null;
            if ($profileImage && $fileName) {
                try {
                    /** @var \Magento\Framework\ObjectManagerInterface $uploader */
                    $uploader = $objectManager->create(
                        'Magento\MediaStorage\Model\File\Uploader',
                        ['fileId' => 'image']
                    );
                    $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
                    /** @var \Magento\Framework\Image\Adapter\AdapterInterface $imageAdapterFactory */
                    $imageAdapterFactory = $objectManager->get('Magento\Framework\Image\AdapterFactory')
                        ->create();
                    $uploader->setAllowRenameFiles(true);
                    $uploader->setFilesDispersion(true);
                    $uploader->setAllowCreateFolders(true);
                    /** @var \Magento\Framework\Filesystem\Directory\Read $mediaDirectory */
                    $mediaDirectory = $objectManager->get('Magento\Framework\Filesystem')
                        ->getDirectoryRead(DirectoryList::MEDIA);

                    $result = $uploader->save(
                        $mediaDirectory
                            ->getAbsolutePath('customform_customform')
                    );

                    $imagePath = $result['file'];
                    $model->setFile('customform_customform'.$result['file']); //Database field name
                } catch (\Exception $e) {
                    if ($e->getCode() == 0) {
                        $this->messageManager->addError($e->getMessage());
                    }
                }
            }

            $model->setData('name', $post['fullName']);
            $model->setData('email', $post['email']);
            $model->setData('phone', $post['phone']);
            $model->setData('metal_type', $post['metal_type']);
            $model->setData('ring_size', $post['ring_size']);
            $model->setData('budget', $post['budget']);
            $model->setData('links_to_design', $post['links_to_design']);
            $model->setData('comments', $post['comments']);
            $model->save();

$uploadedFile =  $baseUrl.'pub/media/customform_customform'.$imagePath;


$this->inlineTranslation->suspend();

            $sender = [
                'name' => $nameAdmin,
                'email' => $emailAdmin
            ];

            $sentToEmail = $post['email'];

            $sentToName = $post['fullName'];


            $transport = $this->_transportBuilder
            ->setTemplateIdentifier('customemail_email_template')
            ->setTemplateOptions(
                [
                    'area' => 'frontend',
                    'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
                ]
                )
                ->setTemplateVars([
                    'name'  => $post['fullName'],
                    'email'  => $post['email'],
                    'phone' => $post['phone'],
                    'metalType' => $post['metal_type'],
                    'ringSize' => $post['ring_size'],
                    'budget' => $post['budget'],
                    'links' => $post['links_to_design'],
                    'uploadedImage' => $uploadedFile,
                    'comments' => $post['comments']
                ])
                ->setFrom($sender)
                ->addTo($sentToEmail,$sentToName)
                //->attachFile($uploadedFileName, $uploadedFile)
                //->addTo('[email protected]','owner')
                ->getTransport();

                $transport->sendMessage();

               $this->inlineTranslation->resume();

        $this->messageManager->addSuccess(
                __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')
            );
        } else {
            $this->messageManager->addError(
                __('Something missing in your details!')
            );
        }
        $resultRedirect->setUrl($this->_redirect->getRefererUrl());
        return $resultRedirect;
    }
}

2 Answers 2

1

I created an extension which allows you to attach a file to the contact form

https://github.com/DominicWatts/ContactAttachment

Take a look at the controller. It has everything you need.

0

Inorder to attach the file in mail, Please follow the below steps

Step #1: Need to extend the core transportbuilder

File path: root/app/Faceless/AttachmentModule/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="\Faceless\AttachmentModule\Magento\Mail\Template\TransportBuilder" />
</config>

Step #2: Introduce the attachment file type in addAttachment() method

File path: root/app/Faceless/AttachmentModule/Magento/Mail/Template;

<?php

namespace Faceless\AttachmentModule\Magento\Mail\Template;

class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder
{
    public function addAttachment($fileName,$attachedName)
    {
        $this->message->createAttachment(
            $fileName,
            'text/csv',
            \Zend_Mime::DISPOSITION_ATTACHMENT,
            \Zend_Mime::ENCODING_BASE64,
            $attachedName
        );
        return $this;
    }
}

NOTE: Here i was used CSV file, you can change the format

Step #3: Inject the class and prepare attachment file with data

private $transportBuilder;
private $csvWriter;
public function __construct(
\Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
\Magento\Framework\File\Csv $csvWriter
) {
    $this->csvWriter    = $csvWriter;
    $this->transportBuilder = $transportBuilder;
}

public function prepareCsv($data)
    { 
    // $filePath = '/var/www/html/magentoRoot 
    // you can get the path from  \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR;
    $data[0] = ['SKU', 'Store', 'Price', 'SpecialPrice', 'Status']; // header for the csv file
    $data[1] = ['prod-1', 'Primary Store', '1000', '500', 'Enabled']; // You can use proper push function for more data
        $this->csvWriter
            ->setEnclosure('"')
            ->setDelimiter(',')
            ->saveData($filePath ,$data);
        return $filePath;
    }

Step #4: Use the below logic where you required - addAttachment(content, filename)

$transport  = $this->transportBuilder
                    ->setTemplateIdentifier('mail_template')
                    ->setTemplateOptions( [
                    'area' => 'frontend',
                    'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
            ])
                    ->setTemplateVars([
                    'name'  => $post['fullName'],
                    'email'  => $post['email'],
                    'phone' => $post['phone'],
                    'metalType' => $post['metal_type'],
                    'ringSize' => $post['ring_size'],
                    'budget' => $post['budget'],
                    'links' => $post['links_to_design'],
                    'uploadedImage' => $uploadedFile,
                    'comments' => $post['comments']
             ])
                    ->setFrom($sender)
                    ->addTo('[email protected]');
                ->addAttachment(file_get_contents($file), 'facelessFilename.csv') : ''; // facelessFilename.csv - attachment name in mail
$transport->getTransport()->sendMessage();

Hope this help you, Please follow this and let me know. Happy to contribute.

1
  • can you share complete proper code of this extension ? Commented Mar 28, 2022 at 12:43

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.