Skip to content

Send attachment with form

I am trying to send an email on Magento 2 with an attachment. Not being a developer I copied a working module, but the email does not start. Below is the error and the code. Can anyone help me?

Error:

main.CRITICAL: Type Error occurred when creating object: LogiconeDiventaRivenditoreControllerIndexSubmitInterceptor, Argument 2 passed to LogiconeDiventaRivenditoreControllerIndexSubmit::__construct() must be an instance of MagentoFrameworkFilesystem, instance of LogiconeDiventaVpeopleMagentoMailTemplateTransportBuilderInterceptor given, called in /var/www/html/generated/code/Logicone/DiventaRivenditore/Controller/Index/Submit/Interceptor.php on line 14 {"report_id":"b1fff39d75dc35fbf57f1806948f5e7f386dee68a8cad0ccc4d0cb12b33821dc","exception":"[object] (Magento\Framework\Exception\RuntimeException(code: 0): Type Error occurred when creating object: Logicone\DiventaRivenditore\Controller\Index\Submit\Interceptor, Argument 2 passed to Logicone\DiventaRivenditore\Controller\Index\Submit::__construct() must be an instance of Magento\Framework\Filesystem, instance of Logicone\DiventaVpeople\Magento\Mail\Template\TransportBuilder\Interceptor given, called in /var/www/html/generated/code/Logicone/DiventaRivenditore/Controller/Index/Submit/Interceptor.php on line 14 at /var/www/html/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php:131)"} []

submit.php

<?php
namespace LogiconeDiventaRivenditoreControllerIndex;

use MagentoFrameworkAppActionContext;
use MagentoFrameworkAppFilesystemDirectoryList;
use MagentoFrameworkAppActionAction;
use MagentoFrameworkFilesystem;
use MagentoFrameworkAppRequestDataPersistorInterface;
use ZendMimeMime;

class Submit extends MagentoFrameworkAppActionAction
{
    
    private $dataPersistor;
    /**
     * @return MagentoFrameworkControllerResultRedirect|MagentoFrameworkViewResultPage
     */

    private $fileUploaderFactory;
    private $fileSystem;
    
    /**
     * @var MagentoFrameworkMailTemplateTransportBuilder
     */
    protected $_transportBuilder;

    /**
     * @var MagentoFrameworkTranslateInlineStateInterface
     */
    protected $inlineTranslation;

    /**
     * @var MagentoFrameworkAppConfigScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var MagentoStoreModelStoreManagerInterface
     */
    protected $storeManager;
    /**
     * @var MagentoFrameworkEscaper
     */
    protected $_escaper;

    protected $_resultRedirectFactory;
    /**
     * @param MagentoFrameworkAppActionContext $context
     * @param MagentoFrameworkMailTemplateTransportBuilder $transportBuilder
     * @param MagentoFrameworkTranslateInlineStateInterface $inlineTranslation
     * @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
     * @param MagentoStoreModelStoreManagerInterface $storeManager
     */
    public function __construct(
        MagentoFrameworkAppActionContext $context,
        Filesystem $fileSystem,
        MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory,
        LogiconeDiventaRivenditoreMagentoMailTemplateTransportBuilder $transportBuilder,
        MagentoFrameworkTranslateInlineStateInterface $inlineTranslation,
        MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoFrameworkEscaper $escaper
    ) {
        parent::__construct($context);
        $this->fileUploaderFactory = $fileUploaderFactory;
        $this->fileSystem = $fileSystem;
        $this->_transportBuilder = $transportBuilder;
        $this->inlineTranslation = $inlineTranslation;
        $this->scopeConfig = $scopeConfig;
        $this->storeManager = $storeManager;
        $this->_escaper = $escaper;
        $this->_resultRedirectFactory=$context->getResultRedirectFactory();
    }

    /**
     * Post user question
     *
     * @return void
     * @throws Exception
     */
    public function execute()
    {
        $resultRedirect = $this->_resultRedirectFactory->create();
        $post = $this->getRequest()->getPostValue();
        if (!$post) {
            $this->_redirect('*/*/');
            return;
        }
        try {

            $storeScope = MagentoStoreModelScopeInterface::SCOPE_STORE;
            $is_enabled = $this->scopeConfig->getValue('diventarivenditore/general/IsEnabled', $storeScope);
            $url = $this->storeManager->getStore()->getBaseUrl();
            $enabled_link = '';
            if($is_enabled == '1') {
                $enabled_link = $url;
            }
            $post['site_link'] = $enabled_link;
            
            $filesData = $this->getRequest()->getFiles('becomevpeople');

            if ($filesData['name']) {
                try {
                     $uploader = $this->fileUploaderFactory->create(['fileId' => 'becomevpeople']);
                     $uploader->setAllowRenameFiles(true);
                     $uploader->setFilesDispersion(true);
                     $uploader->setAllowCreateFolders(true);
                     $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png', 'pdf', 'docx']);
                     $path = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('becomevpeople');
                     $result = $uploader->save($path);
                     $becomevpeople = 'becomevpeople'.$uploader->getUploadedFilename();
                     $filePath = $result['path'].$result['file'];
                     $fileName = $result['name'];
                     $fileType = $result['type'];
                }catch (Exception $e) {
                    $this->inlineTranslation->resume();
                    $this->messageManager->addError(__('File format not supported.'));
                    return $resultRedirect->setPath('*/*/');
                }
            } else {
                 $becomevpeople = '';
                 $filePath = '';
                 $fileName = '';
            }

            $emailSender=$this->scopeConfig->getValue('diventarivenditore/general/SenderField', $storeScope);
            $emailSender = ($emailSender != '') ? explode(",", $emailSender) : '';
            $emailTo = $this->scopeConfig->getValue('diventarivenditore/general/ToField', $storeScope);
            $emailTo = ($emailTo != '') ? explode(",", $emailTo) : '';
            $emailCc = $this->scopeConfig->getValue('diventarivenditore/general/CcField', $storeScope);
            $emailCc = ($emailCc != '') ? explode(",", $emailCc) : '';
            $emailBcc = $this->scopeConfig->getValue('diventarivenditore/general/BccField', $storeScope);
            $emailBcc = ($emailBcc != '') ? explode(",", $emailBcc) : '';

            $postObject = new MagentoFrameworkDataObject();
            $postObject->setData($post);
            $error = false;

            $sender = [
                'name' => $this->_escaper->escapeHtml($post['name'].' '.$post['surname']),
                'email' =>  $emailSender, //$this->_escaper->escapeHtml($post['email']),
            ];

            $templateTo = $this->scopeConfig->getValue('diventarivenditore/general/email_template', $storeScope);
            $transport = $this->_transportBuilder->setTemplateIdentifier($templateTo) // this code we have mentioned in the email_templates.xml
            ->setTemplateOptions(
                [
                    'area' => MagentoFrameworkAppArea::AREA_FRONTEND, // this is using frontend area to get the template file
                    'store' => $this->storeManager->getStore()->getId(),
                ]
            )
                ->setTemplateVars(['data' => $postObject])
                ->setFrom($sender)
                ->addTo($emailTo)
                ->addCc($emailCc)
                ->addBcc($emailBcc)
                ->setReplyTo($this->_escaper->escapeHtml($post['email']),$this->_escaper->escapeHtml($post['name'].' '.$post['surname']))
                ->getTransport();
            
            if(file_exists($filePath) && !empty($filePath)) {
                $html = $transport->getMessage()->getBody()->generateMessage("n");
                $bodyMessage = new ZendMimePart(Mime::encode(quoted_printable_decode($html), 'utf-8', "n"));
                $bodyMessage->type = 'text/html';
                $attachment = $this->_transportBuilder->addAttachment(file_get_contents($filePath), $fileName);
                $bodyPart = new ZendMimeMessage();
                $bodyPart->setParts(array($bodyMessage,$attachment));
                $transport->getMessage()->setBody($bodyPart);
            }
            
            $transport->sendMessage();
            $this->inlineTranslation->resume();
            $this->messageManager->addSuccess(__('Your data sent successfully.'));
            return $resultRedirect->setPath('*/*/');
        }catch (Exception $e) {
            $this->inlineTranslation->resume();
            $this->messageManager->addError(__('There is some error, Try again.'.$e->getMessage().'<br> TRACE:'.$e->getTraceAsString()));
            return $resultRedirect->setPath('*/*/');
        }
    }


}

?>

customform.phtml

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<?php 
    $themeHelper = $this->helper('MGSMpanelHelperData');
    $helperil = $this->helper('LogiconeDiventaRivenditoreHelperData');
    $canUsePanel = $themeHelper->acceptToUsePanel();
    $blockObjCou = $block->getLayout()->createBlock('LogiconeDiventaRivenditoreBlockCountry');
    $blockObjReg = $block->getLayout()->createBlock('LogiconeDiventaRivenditoreBlockRegion');
    $countryList = $blockObjCou->getCountries();
    $regionsList = $blockObjReg->getRegions();
?>
<?php $diventaRivenditoreEnable = $helperil->getGeneralConfig('IsEnabled'); ?>
<?php if ($diventaRivenditoreEnable  == 0) { ?>
    <?php $diventaRivenditoreRedirect = $helperil->getGeneralConfig('ToRedirect'); ?>
    <script language="javascript" type="text/javascript">
        window.location.href = "<?php echo $diventaRivenditoreRedirect; ?>";
    </script>
<?php } else { ?>
    <div class="contact-form-content">
        <div class="row">
            <div class="col-sm-6 col-xs-12 margin-bottom60">
                <h3 class="text-uppercase margin-bottom15"><?php echo __('become a reseller'); ?></h3>
                <p class="sub-title margin-bottom30"><em><?php echo __('To better process your request, we ask you to provide us with some useful data in order to get in touch with our area agent.'); ?></em></p>
                <form id="diventarivenditore-form" class="form contact" method="post" action="<?php echo $block->getBaseUrl()?>diventarivenditore/index/submit" data-mage-init='{"validation": {}}'>
                    <div class="form-group spaceyesno required">
                            <select name="spaceyesno" class="select admin__control-select" data-validate="{required:true}">
                                <option value="">&nbsp;</option>
                                <option value="<?php echo __('Yes'); ?>"><?php echo __('Yes'); ?></option>
                                <option value="<?php echo __('No'); ?>"><?php echo __('No'); ?></option>
                            </select>
                        <label for="spaceyesno"><span><?php  echo __('Do you want to dedicate a space within your store to our collections?') ?></span></label>
                    </div>
                    <div class="form-group businessname required">
                        <label for="name"><?php echo __('Business name'); ?></label>
                        <input name="name" id="name" title="<?php /* @escapeNotVerified */ echo __('Business name') ?>" value="" class="input-text form-control" type="text" data-validate="{required:true}"/>
                    </div>
                    <div class="form-group email required">
                        <label for="email"><?php echo __('Email'); ?></label>
                        <input name="email" id="email" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" value="<?php echo $block->escapeHtml($this->helper('MagentoContactHelperData')->getUserEmail()) ?>" class="input-text form-control" type="email" data-validate="{required:true, 'validate-email':true}"/>
                    </div>
                    <div class="form-group telephone required">
                        <label for="telephone"><?php echo __('Phone'); ?></label>
                        <input name="telephone" id="telephone" title="<?php /* @escapeNotVerified */ echo __('Phone') ?>" value="" class="input-text form-control" type="text" data-validate="{required:true, 'validate-phoneLax':true}"/>
                    </div>
                    <div class="form-group shopyesno required">
                        <label for="shopyesno"><span><?php  echo __('Do you already have a shop?') ?></span></label>
                        <select name="shopyesno" class="select admin__control-select" data-validate="{required:true}">
                            <option value="">&nbsp;</option>
                            <option value="<?php echo __('Yes'); ?>"><?php echo __('Yes'); ?></option>
                            <option value="<?php echo __('No'); ?>"><?php echo __('No'); ?></option>
                        </select>
                        
                    </div>
                    <?php $diventaRivenditoretiponegozio = $helperil->getGeneralConfig('tiponegozio'); ?>
                    <?php $array_tiponegozio = explode(',', $diventaRivenditoretiponegozio); ?>
                    <div class="form-group field tiponegozio required">
                        <label for="tiponegozio"><span><?php  echo __('Tipologia di attività commerciale') ?></span></label>
                        <select name="tiponegozio" onchange="showDiv(this)">
                            <?php foreach ($array_tiponegozio as $tiponegozio) { ?>
                            <option value="<?php echo trim($tiponegozio) ?>"><?php echo trim($tiponegozio) ?></option>
                            <?php } ?>
                        </select>
                    </div>
                    <div id="hidden_div" style="display:none;" class="form-group field altro required">
                        <label for="tiponegozio"><span><?php  echo __('Specificare altra Tipologia') ?></span></label>
                        <input name="altro" id="altro" title="<?php echo __('Specificare altra Tipologia') ?>" value="" class="input-text form-control" type="text" data-validate="{required:true}"/>
                    </div>                  
                    <div style="display:none;" class="form-group field country required">
                        <label for="country"><span><?php echo __('Country') ?></span></label>
                        <select name="country">
                            <?php foreach ($countryList as $key => $country) { ?>
                            <option value="<?php echo $country['value'] ?>"><?php echo $country['value'] ?></option>
                            <?php } ?>
                        </select>
                    </div>
                    <div class="form-group field region required ">
                        <label for="region"><span><?php  echo __('Region') ?></span></label>
                        <select name="region">
                            <?php foreach ($regionsList as $key => $regions) { ?>
                            <option value="<?php echo $regions['value'] ?>"><?php echo $regions['value'] ?></option>
                            <?php } ?>
                        </select>
                    </div>
                    <div class="form-group city required">
                        <label for="city"><?php echo __('City'); ?></label>
                        <input name="city" id="city" title="<?php /* @escapeNotVerified */ echo __('City') ?>" value="" class="input-text form-control" type="text" data-validate="{required:true}"/>
                    </div>
                    <div class="form-group street required">
                        <label for="street"><?php echo __('Street'); ?></label>
                        <input name="street" id="street" title="<?php /* @escapeNotVerified */ echo __('Street') ?>" value="" class="input-text form-control" type="text" data-validate="{required:true}"/>
                    </div>
                    <div class="form-group postcode required">
                        <label for="postcode"><?php echo __('Post code'); ?></label>
                        <input name="postcode" id="postcode" title="<?php /* @escapeNotVerified */ echo __('Post code') ?>" value="" class="input-text form-control" type="text" data-validate="{required:true, 'validate-number':true}"/>
                    </div>
                    <?php $diventaRivenditoreMqShop = $helperil->getGeneralConfig('MqShop'); ?>
                    <?php $array_mqShop = explode(',', $diventaRivenditoreMqShop); ?>
                    <div class="form-group field mqshop required">
                        <label for="mqshop"><span><?php  echo __('Mq Shop') ?></span></label>
                        <select name="mqshop">
                            <?php foreach ($array_mqShop as $mqShop) { ?>
                            <option value="<?php echo trim($mqShop) ?>"><?php echo trim($mqShop) ?></option>
                            <?php } ?>
                        </select>
                    </div>
                    <?php $diventaRivenditoreLocationShops = $helperil->getGeneralConfig('LocationShops'); ?>
                    <?php $array_locationShops = explode(',', $diventaRivenditoreLocationShops); ?>
                    <div class="form-group field locationshops required">
                        <label for="locationshops"><span><?php  echo __('Location Shops') ?></span></label>
                        <select name="locationshops" onchange="showDiv(this)">
                            <?php foreach ($array_locationShops as $locationShops) { ?>
                            <option value="<?php echo trim($locationShops) ?>"><?php echo trim($locationShops) ?></option>
                            <?php } ?>
                        </select>
                    </div>
                    <?php $diventaRivenditoreLocationCity = $helperil->getGeneralConfig('LocationCity'); ?>
                    <?php $array_locationCity = explode(',', $diventaRivenditoreLocationCity); ?>
                    <div id="hidden_div" style="display:none;" class="form-group field locationcity required">
                        <label for="locationcity"><span><?php  echo __('Location City') ?></span></label>
                        <select name="locationcity">
                            <option value="<?php echo __(' '); ?>"><?php echo __(' '); ?></option>
                            <?php foreach ($array_locationCity as $locationCity) { ?>
                            <option value="<?php echo trim($locationCity) ?>"><?php echo trim($locationCity) ?></option>
                            <?php } ?>
                        </select>
                    </div>

                    <?php $diventaRivenditoreHowfindus = $helperil->getGeneralConfig('Howfindus'); ?>
                    <?php $array_howfindus = explode(',', $diventaRivenditoreHowfindus); ?>
                    <div class="form-group field howfindus required">
                        <label for="howfindus"><span><?php  echo __('How did you hear about our company?') ?></span></label>
                        <select name="howfindus" data-validate="{required:true}">
                            <?php foreach ($array_howfindus as $howfindus) { ?>
                            <option value="<?php echo trim($howfindus) ?>"><?php echo trim($howfindus) ?></option>
                            <?php } ?>
                        </select>
                    </div>
                    
                    <div class="form-group howfindother required" style="display:none">
                        <label for="howfindother"><?php echo __('Other'); ?></label>
                        <input name="howfindother" id="howfindother" title="<?php /* @escapeNotVerified */ echo __('Other') ?>" value="" class="input-text form-control" type="text" data-validate="{required:true}" />
                    </div>  

                    <div class="form-group becomevpeople shopimage">
                        <label for="becomevpeople"><?php echo __('Shop Image (max 5 MB)'); ?></label> 
                        <input id="file-btn" accept=".jpg, .jpeg, .pdf" name="becomevpeople" type="file" value="">
                        <div id="shopimage_file_error" class="mage-error message-error error message" style="display:none;"><?php echo __('File is too large'); ?></div>
                    </div>                  

                    <div class="diventarivenditore">
                        <?php echo $this->getLayout()->createBlock('MagentoCheckoutAgreementsBlockAgreements')->setTemplate('additional_agreements.phtml') ->toHtml() ?>
                    </div>
                    <div class="form-group">
                        <button type="submit" name="contact-frm" id="contact-frm" class="action submit btn btn-primary"><?php /* @escapeNotVerified */ echo __('Send Messages') ?></button>
                    </div>
                </form>
            </div>
            <div class="col-sm-6 col-xs-12 margin-bottom60">
                <!-- Static block contact_page_custom_block -->
                <?php echo $this->getLayout()->createBlock('MagentoCmsBlockBlock')->setBlockId('contact_page_custom_block')->setCanUsePanel($canUsePanel)->toHtml(); ?>
            </div>
        </div>
    </div>

<script type="text/javascript">
require(['jquery'], function($) {
    $(document).ready(function() {
        $('select[name="howfindus"]').on('change', function() {
            var options = $(this).find('option');
            // Controllo quale sia l'ultimo valore
            var lastOptionValue = options.last().val();
            // Mostra/nascondi div in base al valore selezionato
            if ($(this).val() === lastOptionValue) {                
                $('.howfindother').slideDown();
            } else {
                $('.howfindother').slideUp();
            }
        });
        // Upload control size
        var uploadField = document.getElementById("file-btn");
        uploadField.onchange = function() {
            if(this.files[0].size > 5294304){
                $('#shopimage_file_error').show();
                this.value = "";
            }else{
                $('#shopimage_file_error').hide();
            };
        };

    });
});
</script>   
    <script type="text/javascript">
        /*function showDiv(select){
            var i = ' ';
            i = '<?php echo trim($array_locationShops[2]); ?>';
           if(select.value == i){
            document.getElementById('hidden_div').style.display = "block";
           } else{
            document.getElementById('hidden_div').style.display = "none";
           }
        } */
    </script>
    <script type="text/javascript">
        /*function showDiv(select){
            var i = ' ';
            i = '<?php echo trim($array_tiponegozio[1]); ?>';
           if(select.value == i){
            document.getElementById('hidden_div').style.display = "block";
           } else{
            document.getElementById('hidden_div').style.display = "none";
           }
        } */
    </script>
    <?php $diventaRivenditoreTermsEnable = $helperil->getGeneralConfig('display_terms'); ?>
    <style>
        <?php for ($i = 1; $i <= 100; $i++) { ?>
            <?php if ($i != $diventaRivenditoreTermsEnable) { ?>
                .diventarivenditore #agreement__<?php echo $i ;?> {
                    display:none;
                }
            <?php } ?>
        <?php } ?>
    </style>
<?php } ?>

Any ideas? Thank you