1

I made a custom module which has a form for customer, in which customer fill his info, upload multiple files and on Submit, Admin receives an email with customer info and files, but my problem is when customer send multiple files, Admin receive only one file in email attachment, also multiple file saved in pub/media, but not receiving more then one file in email... Here is my code.

/app/code/Custom/Procard/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
{
    /**
     * @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;
    /**
     * 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
     */
    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->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';

        $post['address'] = $address;
        $post['city'] = $city;

        $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;
                    }

                    $mimeType = mime_content_type($attachment);

                    $postObject = new \Magento\Framework\DataObject();
                    $postObject->setData($post);

                    $this->inlineTranslation->suspend();
                    $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;
        }
    }
}

/app/code/Custom/Procard/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;
    }
}

/app/code/Custom/Procard/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;
    }
}

Your Answer

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

Browse other questions tagged or ask your own question.