Question

I made a Module which has a form for customer to send his/her info with multiple images, Images saved to media folder on Submit also I get success message, but the Store Owner don't receive mail please review my code if you get any issue.

app/code/[Vendor]/[Module]/Controller/Index/Post.php

<?php
/**
 *
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace [Vendor]\[Module]\Controller\Index;

use Magento\Contact\Model\ConfigInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\App\Filesystem\DirectoryList;

class Post extends \Magento\Contact\Controller\Index
{
    /**
     * @var DataPersistorInterface
     */
    private $dataPersistor;   

    /**
     * Post user question
     *
     * @return void
     * @throws \Exception
     */
    private $scopeConfig;

    /**
     * @var \Magento\Directory\Model\CountryFactory
     */
    private $countryFactory;

    private $inlineTranslation;
    /**
     * @var \Magento\Framework\Mail\Template\TransportBuilder
     */
    protected $_transportBuilder;

    /**
     * @var \Magento\Directory\Model\Region
     */
    private $region;

    /**
     * @var \Magento\Framework\Filesystem
     */
    protected $_filesystem;

    /**
     * Post constructor.
     * @param Context $context
     * @param ConfigInterface $contactsConfig
     * @param \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder
     * @param ScopeConfigInterface $scopeConfig
     * @param \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation
     * @param \Magento\Directory\Model\CountryFactory $countryFactory
     * @param \Magento\Directory\Model\Region $region
     */
    public function __construct(
        Context $context,
        ConfigInterface $contactsConfig,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        ScopeConfigInterface $scopeConfig,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Magento\Directory\Model\CountryFactory $countryFactory,
        \Magento\Directory\Model\Region $region,
        \Magento\Framework\Filesystem $filesystem
    ) {
        parent::__construct($context, $contactsConfig);
        $this->_transportBuilder = $transportBuilder;
        $this->scopeConfig = $scopeConfig;
        $this->inlineTranslation = $inlineTranslation;
        $this->countryFactory = $countryFactory;
        $this->region = $region;
        $this->_filesystem = $filesystem;
    }

    /**
     * @return bool|\Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface
     */
    public function execute() {
      $post = $this->getRequest()->getPostValue();
      $postObject = new \Magento\Framework\DataObject();
      $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
      $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
      $webURl = $storeManager->getStore()->getBaseUrl();

      $name = trim($post['name']);
      $email = trim($post['email']);

      $address = (isset($post['address']) && !empty($post['address'])) ? trim($post['address']) : 'N/A';
      $city = (isset($post['city']) && !empty($post['city'])) ? trim($post['city']) : 'N/A';
      $state = (isset($post['region']) && !empty($post['region'])) ? $this->getRegionName(trim($post['region'])) : "N/A";
      $country = (isset($post['country_id']) && !empty($post['country_id'])) ? $this->getCountryName($post['country_id']) : 'N/A';
      $zip = (isset($post['zip']) && !empty($post['zip']) ) ? trim($post['zip']) : 'N/A';
      $tel = (isset($post['tel']) && !empty($post['tel'])) ? trim($post['tel']) : 'N/A';
      $employer = (isset($post['employer']) && !empty($post['employer'])) ? trim($post['employer']) : 'N/A';
      $jobtitle = (isset($post['jobtitle']) && !empty($post['jobtitle'])) ? trim($post['jobtitle']) : 'N/A';

      $post['address'] = $address;
      $post['city'] = $city;
      $post['state'] = $state;
      $post['zip'] = $zip;
      $post['tel'] = $tel;
      $post['employer'] = $employer;
      $post['jobtitle'] = $jobtitle;

      $postObject->setData($post);

      //print_r($post); die;

      $fileName = '';
      $attachment = '';

      // Count # of uploaded files in array
      $total = count($_FILES['attachment']['name']);

      // Loop through each file
      for( $i=0 ; $i < $total ; $i++ ) {
        if (isset($_FILES['attachment']['name'][$i]) && $_FILES['attachment']['name'][$i] != '') {
            try {
                $fileName = $_FILES['attachment']['name'][$i];
                $fileExt = strtolower(substr(strrchr($fileName, ".") ,1));
                $fileNamewoe = explode('.', $fileName);
                $fileName = str_replace(' ', '', $fileNamewoe[0]) . time() . '.' . $fileExt;

                $mediapath = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
                if(move_uploaded_file($_FILES['attachment']['tmp_name'][$i], $mediapath . 'procard/'.$fileName)){
                    $attachment = $mediapath . 'procard/'.$fileName;
                }

            } catch (Exception $e) {
                $this->messageManager->addError($e->getMessage());
                $error = true;
            }
        }
      }

      $templateId = 2;

      $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;

      if($attachment != ''){

          $transports = $this->_transportBuilder->setTemplateIdentifier($templateId)
          ->setTemplateOptions(
              [
                  'area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE,
                  'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
              ]
          )
          ->setTemplateVars(['data' => $postObject])
          ->setFrom($this->scopeConfig->getValue(self::XML_PATH_EMAIL_SENDER, $storeScope))
          ->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_RECIPIENT, $storeScope))
          ->addAttachment(file_get_contents($attachment),$fileName)
          ->getTransport();
      }
      else{

          $transports = $this->_transportBuilder->setTemplateIdentifier($templateId)
          ->setTemplateOptions(
              [
                  'area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE,
                  'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
              ]
          )
          ->setTemplateVars(['data' => $postObject])
          ->setFrom($this->scopeConfig->getValue(self::XML_PATH_EMAIL_SENDER, $storeScope))
          ->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_RECIPIENT, $storeScope))
          ->getTransport();
      }

      try {
          $transports->sendMessage();
      } catch (LocalizedException $exception) {
          $this->messageManager->addError($exception->getMessage());
          $this->_redirect($this->_redirect->getRefererUrl());
          return false;
      }
      $this->inlineTranslation->resume();

      $this->messageManager->addSuccess(
        __('Success!<br>Your Pro Card application has been received. <br> We will get back to you soon.')
      );

      $this->getDataPersistor()->clear('pro-card');
      $this->_redirect($this->_redirect->getRefererUrl());
    }    

    /**
     * Get Data Persistor
     *
     * @return DataPersistorInterface
     */
    private function getDataPersistor()
    {
        if ($this->dataPersistor === null) {
            $this->dataPersistor = ObjectManager::getInstance()
                ->get(DataPersistorInterface::class);
        }

        return $this->dataPersistor;
    }

    /**
     * @param $countryCode
     * @return string
     */
    public function getCountryName($countryCode){
        $country = $this->countryFactory->create()->loadByCode($countryCode);
        return $country->getName();
    }

    /**
     * @param $regionId
     * @return bool|string
     */
    public function getRegionName($regionId)
    {
        try {
            $region = $this->region->load($regionId);
            return $region->getName();
        } catch (NoSuchEntityException $exception) {
            return false;
        }
    }
}

app/code/[Vendor]/[Module]/Mail/Template/TransportBuilder.php

<?php
namespace [Vendor]\[Module]\Mail\Template;

class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder
{
    public function addAttachment(
                            $body,
                            $mimeType = \Zend_Mime::TYPE_OCTETSTREAM,
                            $disposition = \Zend_Mime::DISPOSITION_ATTACHMENT,
                            $encoding = \Zend_Mime::ENCODING_BASE64,
                            $filename = null)
    {
        //$this->message->createAttachment($body, $mimeType, $disposition, $encoding, $filename);
        $this->message->createCustomAttachment($body, $mimeType, $disposition, $encoding, $filename);
        return $this;
    }
}

app/code/[Vendor]/[Module]/Mail/Message.php

<?php

namespace [Vendor]\[Module]\Mail;

use Zend\Mime\Mime;
use Zend\Mime\Part;

/**
 * Class Message for email transportation
 */
class Message implements \Magento\Framework\Mail\MailMessageInterface
{
    /**
     * @var \Zend\Mail\Message
     */
    private $zendMessage;
    private $attachment;

    /**
     * Message type
     *
     * @var string
     */
    private $messageType = self::TYPE_TEXT;

    /**
     * Initialize dependencies.
     *
     * @param string $charset
     */
    public function __construct($charset = 'utf-8')
    {
        $this->zendMessage = new \Zend\Mail\Message();
        $this->zendMessage->setEncoding($charset);
    }

    /**
     * @inheritdoc
     *
     * @deprecated 101.0.8
     * @see \Magento\Framework\Mail\Message::setBodyText
     * @see \Magento\Framework\Mail\Message::setBodyHtml
     */
    public function setMessageType($type)
    {
        $this->messageType = $type;
        return $this;
    }

    /**
     * @inheritdoc
     *
     * @deprecated 101.0.8
     * @see \Magento\Framework\Mail\Message::setBodyText
     * @see \Magento\Framework\Mail\Message::setBodyHtml
     */
    public function setBody($body)
    {
        if (is_string($body) && $this->messageType === \Magento\Framework\Mail\MailMessageInterface::TYPE_HTML) {
            $body = self::createHtmlMimeFromString($body);
        }
        $this->zendMessage->setBody($body);
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function setSubject($subject)
    {
        $this->zendMessage->setSubject($subject);
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function getSubject()
    {
        return $this->zendMessage->getSubject();
    }

    /**
     * @inheritdoc
     */
    public function getBody()
    {
        return $this->zendMessage->getBody();
    }

    /**
     * @inheritdoc
     *
     * @deprecated 102.0.1 This function is missing the from name. The
     * setFromAddress() function sets both from address and from name.
     * @see setFromAddress()
     */
    public function setFrom($fromAddress)
    {
        $this->setFromAddress($fromAddress, null);
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function setFromAddress($fromAddress, $fromName = null)
    {
        $this->zendMessage->setFrom($fromAddress, $fromName);
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function addTo($toAddress)
    {
        $this->zendMessage->addTo($toAddress);
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function addCc($ccAddress)
    {
        $this->zendMessage->addCc($ccAddress);
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function addBcc($bccAddress)
    {
        $this->zendMessage->addBcc($bccAddress);
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function setReplyTo($replyToAddress)
    {
        $this->zendMessage->setReplyTo($replyToAddress);
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function getRawMessage()
    {
        return $this->zendMessage->toString();
    }

    /**
     * Create HTML mime message from the string.
     *
     * @param string $htmlBody
     * @return \Zend\Mime\Message
     */
    private function createHtmlMimeFromString($htmlBody)
    {
        $htmlPart = new Part($htmlBody);
        $htmlPart->setCharset($this->zendMessage->getEncoding());
        $htmlPart->setType(Mime::TYPE_HTML);
        $mimeMessage = new \Zend\Mime\Message();
        $mimeMessage->addPart($htmlPart);
        if ($this->attachment) {
            $mimeMessage->addPart($this->attachment);
        }

        return $mimeMessage;
    }

    /**
     * @inheritdoc
     */
    public function setBodyHtml($html)
    {
        $this->setMessageType(self::TYPE_HTML);
        return $this->setBody($html);
    }

    /**
     * @inheritdoc
     */
    public function setBodyText($text)
    {
        $this->setMessageType(self::TYPE_TEXT);
        return $this->setBody($text);
    }

    public function createCustomAttachment($body, $mimeType, $disposition, $encoding, $filename){
        $attachment = new Part($body);
        $attachment->setType($mimeType);
        $attachment->setDisposition($disposition);
        $attachment->setEncoding($encoding);
        $attachment->setFileName($filename);
        $this->attachment = $attachment;
        return $this;
    }
}
Was it helpful?

Solution

I found my answer it works for Magento 2.3.2 I've tried it in 2.3.3 but its not working, so BTW my Magento version is 2.3.2:

First You have to override 2 file with below content in it:

/vendor/magento/framework/Mail/Template/TransportBuilder.php

<?php
namespace Custom\Procard\Mail\Template;
/**
 * TransportBuilder class
 */
class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder
{
    /**
     * @var \Custom\Procard\Mail\Message
     */
    protected $message;

    /**
     * Add an attachment to the message.
     *
     * @param string $content
     * @param string $fileName
     * @param string $fileType
     * @return $this
     */
    public function addAttachment($content, $fileName, $fileType)
    {
        $this->message->setBodyAttachment($content, $fileName, $fileType);
        return $this;
    }

    /**
     * After all parts are set, add them to message body.
     *
     * @return $this
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function prepareMessage()
    {
        parent::prepareMessage();
        $this->message->setPartsToBody();
        return $this;
    }
    /**
     * Set mail from address
     * @param string|array $from
     * @return $this
     */
    public function setFrom($from)
    {
        $result = $this->_senderResolver->resolve($from);
        $this->message->setFrom($result['email'], $result['name']);
        return $this;
    }
}

/vendor/magento/framework/Mail/Message.php

<?php
namespace Custom\Procard\Mail;
use Zend\Mime\Part;
use Zend\Mime\Mime;
use Zend\Mime\PartFactory;
use Zend\Mail\MessageFactory as MailMessageFactory;
use Zend\Mime\MessageFactory as MimeMessageFactory;
/**
 * Message class
 */
class Message extends \Magento\Framework\Mail\Message implements \Magento\Framework\Mail\MailMessageInterface
{
    /**
     * @var \Zend\Mime\PartFactory
     */
    protected $partFactory;
    /**
     * @var \Zend\Mime\MessageFactory
     */
    protected $mimeMessageFactory;
    /**
     * @var \Zend\Mail\Message
     */
    private $zendMessage;
    /**
     * @var \Zend\Mime\Part[]
     */
    protected $parts = [];
    /**
     * Message constructor.
     *
     * @param \Zend\Mime\PartFactory $partFactory
     * @param \Zend\Mime\MessageFactory $mimeMessageFactory
     * @param string $charset
     */
    public function __construct(
        PartFactory $partFactory,
        MimeMessageFactory $mimeMessageFactory,
        $charset = 'utf-8'
    ) {
        $this->partFactory = $partFactory;
        $this->mimeMessageFactory = $mimeMessageFactory;
        $this->zendMessage = MailMessageFactory::getInstance();
        $this->zendMessage->setEncoding($charset);
        parent::__construct($charset);
    }
    /**
     * Add the HTML mime part to the message.
     * @param string $content
     * @return $this
     */
    public function setBodyText($content)
    {
        $textPart = $this->partFactory->create();
        $textPart->setContent($content)
            ->setType(Mime::TYPE_TEXT)
            ->setEncoding(Mime::ENCODING_QUOTEDPRINTABLE)
            ->setCharset($this->zendMessage->getEncoding());
        $this->parts[] = $textPart;
        return $this->setBody($content);
    }
    /**
     * Add the text mime part to the message.
     * @param string $content
     * @return $this
     */
    public function setBodyHtml($content)
    {
        $htmlPart = $this->partFactory->create();
        $htmlPart->setContent($content)
            ->setType(Mime::TYPE_HTML)
            ->setEncoding(Mime::ENCODING_QUOTEDPRINTABLE)
            ->setCharset($this->zendMessage->getEncoding());
        $this->parts[] = $htmlPart;
        // return $this->setBody($content);
    }
    /**
     * Add the attachment mime part to the message.
     *
     * @param string $content
     * @param string $fileName
     * @param string $fileType
     * @return $this
     */
    public function setBodyAttachment($content, $fileName, $fileType)
    {
        $attachmentPart = $this->partFactory->create();
        $attachmentPart->setContent($content)
            ->setType($fileType)
            ->setFileName($fileName)
            ->setDisposition(Mime::DISPOSITION_ATTACHMENT)
            ->setEncoding(Mime::ENCODING_BASE64);
        $this->parts[] = $attachmentPart;
        return $this;
    }
    /**
     * Set parts to Zend message body.
     *
     * @return $this
     */
    public function setPartsToBody()
    {
        $mimeMessage = $this->mimeMessageFactory->create();
        $mimeMessage->setParts($this->parts);
        $this->zendMessage->setBody($mimeMessage);
        return $this;
    }
    /**
     * {@inheritdoc}
     *
     * @deprecated
     * @see \Magento\Framework\Mail\Message::setBodyText
     * @see \Magento\Framework\Mail\Message::setBodyHtml
     */
    public function setBody($body)
    {
        if (is_string($body)) {
            $body = $this->createHtmlMimeFromString($body);
        }
        $this->zendMessage->setBody($body);
        return $this;
    }
    /**
     * {@inheritdoc}
     */
    public function setSubject($subject)
    {
        $this->zendMessage->setSubject($subject);
        return $this;
    }
    /**
     * Create HTML mime message from the string.
     * @param string $htmlBody
     * @return \Zend\Mime\Message
     */
    private function createHtmlMimeFromString($htmlBody)
    {
        $htmlPart = new Part($htmlBody);
        $htmlPart->setCharset($this->zendMessage->getEncoding());
        $htmlPart->setType(Mime::TYPE_HTML);
        $mimeMessage = new \Zend\Mime\Message();
        $mimeMessage->addPart($htmlPart);
        $this->parts[] = $htmlPart;
        return $mimeMessage;
    }
    /**
     * {@inheritdoc}
     */
    public function getSubject()
    {
        return $this->zendMessage->getSubject();
    }
    /**
     * {@inheritdoc}
     */
    public function getBody()
    {
        return $this->zendMessage->getBody();
    }
    /**
     * {@inheritdoc}
     */
    public function setFrom($fromAddress)
    {
        $this->zendMessage->setFrom($fromAddress);
        return $this;
    }
    /**
     * @inheritdoc
     */
    public function setFromAddress($fromAddress, $fromName = null)
    {
        $this->zendMessage->setFrom($fromAddress, $fromName);
        return $this;
    }
    /**
     * {@inheritdoc}
     */
    public function addTo($toAddress)
    {
        $this->zendMessage->addTo($toAddress);
        return $this;
    }
    /**
     * {@inheritdoc}
     */
    public function addCc($ccAddress)
    {
        $this->zendMessage->addCc($ccAddress);
        return $this;
    }
    /**
     * {@inheritdoc}
     */
    public function addBcc($bccAddress)
    {
        $this->zendMessage->addBcc($bccAddress);
        return $this;
    }
    /**
     * {@inheritdoc}
     */
    public function setReplyTo($replyToAddress)
    {
        $this->zendMessage->setReplyTo($replyToAddress);
        return $this;
    }
    /**
     * {@inheritdoc}
     */
    public function getRawMessage()
    {
        return $this->zendMessage->toString();
    }
    /**
     * @inheritDoc
     */
    public function setMessageType($type)
    {
        return $this;
    }
}

Now you need a controller to send your post values with email attachment so I'll share mine controller, you can customize as per your need. app/code/[Vendor]/[Module]/Controller/Index/Post.php

<?php
namespace Custom\Procard\Controller\Index;

use Magento\Store\Model\StoreManagerInterface;
use Magento\Contact\Model\ConfigInterface;
use Magento\Contact\Model\MailInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Area;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\Framework\Translate\Inline\StateInterface;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\DataObject;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Custom\Procard\Mail\Template\TransportBuilder;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Filesystem\Io\File;
use Magento\Framework\Controller\ResultFactory;
/**
 * Post controller class
 */
class Post extends \Magento\Contact\Controller\Index\Post
{
    const FOLDER_LOCATION = 'contactattachment';
    /**
     * @var DataPersistorInterface
     */
    private $dataPersistor;
    /**
     * @var Context
     */
    private $context;
    /**
     * @var MailInterface
     */
    private $mail;
    /**
     * @var LoggerInterface
     */
    private $logger;
    /**
     * @var UploaderFactory
     */
    private $fileUploaderFactory;
    /**
     * @var Filesystem
     */
    private $fileSystem;
    /**
     * @var StateInterface
     */
    private $inlineTranslation;
    /**
     * @var ConfigInterface
     */
    private $contactsConfig;
    /**
     * @var TransportBuilder
     */
    private $transportBuilder;
    /**
     * @var StoreManagerInterface
     */
    private $storeManager;
    /**
     * @var \Magento\Directory\Model\Region
     */
    private $region;
    /**
     * @var \Magento\Directory\Model\CountryFactory
     */
    private $countryFactory;
    /**
     * Post constructor.
     * @param Context $context
     * @param MailInterface $mail
     * @param DataPersistorInterface $dataPersistor
     * @param LoggerInterface|null $logger
     * @param UploaderFactory $fileUploaderFactory
     * @param Filesystem $fileSystem
     * @param StateInterface $inlineTranslation
     * @param ConfigInterface $contactsConfig
     * @param TransportBuilder $transportBuilder
     * @param \Magento\Directory\Model\CountryFactory $countryFactory
     * @param \Magento\Directory\Model\Region $region
     */
    public function __construct(Context $context, MailInterface $mail, DataPersistorInterface $dataPersistor, LoggerInterface $logger = null, UploaderFactory $fileUploaderFactory, Filesystem $fileSystem, StateInterface $inlineTranslation, ConfigInterface $contactsConfig, TransportBuilder $transportBuilder, StoreManagerInterface $storeManager, ScopeConfigInterface $scopeConfig, \Magento\Directory\Model\CountryFactory $countryFactory, \Magento\Directory\Model\Region $region, File $file)
    {
        $this->context = $context;
        $this->mail = $mail;
        $this->dataPersistor = $dataPersistor;
        $this->logger = $logger ? : ObjectManager::getInstance()->get(LoggerInterface::class);
        $this->fileUploaderFactory = $fileUploaderFactory;
        $this->fileSystem = $fileSystem;
        $this->inlineTranslation = $inlineTranslation;
        $this->contactsConfig = $contactsConfig;
        $this->transportBuilder = $transportBuilder;
        $this->storeManager = $storeManager;
        $this->countryFactory = $countryFactory;
        $this->region = $region;
        $this->scopeConfig = $scopeConfig;
        $this->file = $file;
        parent::__construct($context, $contactsConfig, $mail, $dataPersistor, $logger);
    }
    /**
     * Post user question
     * @return Redirect
     */
    public function execute()
    {
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        $post = $this->getRequest()->getPostValue();
        $senderEmail = "partab.saifuddin@gmail.com";
        $senderName = "Partab Saif";
        $recipientEmail = "partab.saifuddin@gmail.com";

        $templateId = 3; // Enter your email template identifier here
        $requestData = array();

        $name = trim($post['name']);
        $email = trim($post['email']);

        $address = (isset($post['address']) && !empty($post['address'])) ? trim($post['address']) : 'N/A';
        $city = (isset($post['city']) && !empty($post['city'])) ? trim($post['city']) : 'N/A';
        $state = (isset($post['region']) && !empty($post['region'])) ? $this->getRegionName(trim($post['region'])) : "N/A";
        $country = (isset($post['country_id']) && !empty($post['country_id'])) ? $this->getCountryName($post['country_id']) : 'N/A';
        $zip = (isset($post['zip']) && !empty($post['zip'])) ? trim($post['zip']) : 'N/A';
        $tel = (isset($post['tel']) && !empty($post['tel'])) ? trim($post['tel']) : 'N/A';
        $employer = (isset($post['employer']) && !empty($post['employer'])) ? trim($post['employer']) : 'N/A';
        $jobtitle = (isset($post['jobtitle']) && !empty($post['jobtitle'])) ? trim($post['jobtitle']) : 'N/A';

        $post['address'] = $address;
        $post['city'] = $city;
        $post['state'] = $state;
        $post['zip'] = $zip;
        $post['tel'] = $tel;
        $post['employer'] = $employer;
        $post['jobtitle'] = $jobtitle;

        $fileName = '';
        $attachment = '';

        // Count # of uploaded files in array
        $total = count($_FILES['attachment']['name']);

        // Loop through each file
        for ($i = 0;$i < $total;$i++)
        {
            if (isset($_FILES['attachment']['name'][$i]) && $_FILES['attachment']['name'][$i] != '')
            {
                try
                {
                    $fileName = $_FILES['attachment']['name'][$i];
                    $fileExt = strtolower(substr(strrchr($fileName, ".") , 1));
                    $fileNamewoe = explode('.', $fileName);
                    $fileName = str_replace(' ', '', $fileNamewoe[0]) . time() . '.' . $fileExt;

                    $mediapath = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
                    if (move_uploaded_file($_FILES['attachment']['tmp_name'][$i], $mediapath . 'procard/' . $fileName))
                    {
                        $attachment = $mediapath . 'procard/' . $fileName;
                    }

                    $postObject = new \Magento\Framework\DataObject();
                    $postObject->setData($post);
                    $mimeType = mime_content_type($attachment);
                    $this->inlineTranslation->suspend();
                    $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
                    $transport = $this->transportBuilder
                        ->setTemplateIdentifier($templateId)
                        ->setTemplateOptions(
                            [
                                'area' => Area::AREA_FRONTEND,
                                'store' => $this->storeManager->getStore()->getId(), 
                            ])
                        ->setTemplateVars(['data' => $postObject])
                        ->setFrom(['name' => $senderName, 'email' => $senderEmail])
                        ->addTo($recipientEmail)
                        ->addAttachment(file_get_contents($attachment), $fileName, $mimeType)
                        ->getTransport();

                }
                catch(Exception $e)
                {
                    $this->messageManager->addError($e->getMessage());
                    $error = true;
                }
            }
        }
        try
        {
            $transport->sendMessage();
            $this->inlineTranslation->resume();

            $this->messageManager->addSuccess(__('Success!<br>Your Pro Card application has been received. <br> We will get back to you soon.'));
            $this->getDataPersistor()->clear('pro-card');
            $resultRedirect->setUrl($this->_redirect->getRefererUrl());
            return $resultRedirect;

        }
        catch(\Exception $e)
        {
            $this->messageManager->addError(__('Something went wrong. Please try again later.'));
            $resultRedirect->setUrl($this->_redirect->getRefererUrl());
            return $resultRedirect;
        }
    }

    /**
     * Get Data Persistor
     *
     * @return DataPersistorInterface
     */
    private function getDataPersistor()
    {
        if ($this->dataPersistor === null)
        {
            $this->dataPersistor = ObjectManager::getInstance()
                ->get(DataPersistorInterface::class);
        }

        return $this->dataPersistor;
    }

    /**
     * @param $countryCode
     * @return string
     */
    public function getCountryName($countryCode)
    {
        $country = $this->countryFactory->create()->loadByCode($countryCode);
        return $country->getName();
    }

    /**
     * @param $regionId
     * @return bool|string
     */
    public function getRegionName($regionId)
    {
        try
        {
            $region = $this->region->load($regionId);
            return $region->getName();
        }
        catch(NoSuchEntityException $exception)
        {
            return false;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top