1

I have extended contact email form and added few fields(Refer screenshot)

enter image description here

Under subject field there are 3 options, based on the subject selected the email should be send to multiple users.

For example, if option 1 is selected it should be sent to only aaa@gmail.com,ccc@gamil.com. If Option 2 is selected it should be sent to only bbb@gmail.com, eee@gmail.com

My controller file

/var/www/html/ajaffe/app/code/Amy/Contactform/Controller/Index/Post.php

<?php
/**
 *
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Amy\Contactform\Controller\Index;

use Magento\Contact\Model\ConfigInterface;
use Magento\Contact\Model\MailInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\HTTP\PhpEnvironment\Request;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\DataObject;

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

    /**
     * @var Context
     */
    private $context;

    /**
     * @var MailInterface
     */
    private $mail;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @param Context $context
     * @param ConfigInterface $contactsConfig
     * @param MailInterface $mail
     * @param DataPersistorInterface $dataPersistor
     * @param LoggerInterface $logger
     */
    public function __construct(
        Context $context,
        ConfigInterface $contactsConfig,
        MailInterface $mail,
        DataPersistorInterface $dataPersistor,
        LoggerInterface $logger = null
    ) {
        parent::__construct($context, $contactsConfig);
        $this->context = $context;
        $this->mail = $mail;
        $this->dataPersistor = $dataPersistor;
        $this->logger = $logger ?: ObjectManager::getInstance()->get(LoggerInterface::class);
    }

    /**
     * Post user question
     *
     * @return Redirect
     */
    public function execute()
    {
        if (!$this->isPostRequest()) {
            return $this->resultRedirectFactory->create()->setPath('*/*/');
        }
        try {
            $this->sendEmail($this->validatedParams());
            $this->messageManager->addSuccessMessage(
                __('Thanks for contacting us. Your inquiry was submitte and will be responded to you as soon as possible.')
            );
            $this->dataPersistor->clear('contact_us');
        } catch (LocalizedException $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
            $this->dataPersistor->set('contact_us', $this->getRequest()->getParams());
        } catch (\Exception $e) {
            $this->logger->critical($e);
            $this->messageManager->addErrorMessage(
                __('An error occurred while processing your form. Please try again later.')
            );
            $this->dataPersistor->set('contact_us', $this->getRequest()->getParams());
        }
        return $this->resultRedirectFactory->create()->setPath('contact/index');
    }

    /**
     * @param array $post Post data from contact form
     * @return void
     */
    private function sendEmail($post)
    {
        $this->mail->send(
            $post['subject'], 
            $post['email'],
            ['data' => new DataObject($post)]
        );
    }

    /**
     * @return bool
     */
    private function isPostRequest()
    {
        /** @var Request $request */
        $request = $this->getRequest();
        return !empty($request->getPostValue());
    }

    /**
     * @return array
     * @throws \Exception
     */
    private function validatedParams()
    {
        $request = $this->getRequest();
        if (trim($request->getParam('name')) === '') {
            throw new LocalizedException(__('Name is missing'));
        }
        if (trim($request->getParam('comment')) === '') {
            throw new LocalizedException(__('Comment is missing'));
        }
        if (false === \strpos($request->getParam('email'), '@')) {
            throw new LocalizedException(__('Invalid email address'));
        }
        if (trim($request->getParam('hideit')) !== '') {
            throw new \Exception();
        }

        return $request->getParams();
    }
}

/var/www/html/ajaffe/app/code/Amy/Contactform/Model/Mail.php

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Amy\Contactform\Model;

use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\Area;

class Mail implements MailInterface
{
    /**
     * @var ConfigInterface
     */
    private $contactsConfig;

    /**
     * @var TransportBuilder
     */
    private $transportBuilder;

    /**
     * @var StateInterface
     */
    private $inlineTranslation;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * Initialize dependencies.
     *
     * @param ConfigInterface $contactsConfig
     * @param TransportBuilder $transportBuilder
     * @param StateInterface $inlineTranslation
     * @param StoreManagerInterface|null $storeManager
     */
    public function __construct(
        ConfigInterface $contactsConfig,
        TransportBuilder $transportBuilder,
        StateInterface $inlineTranslation,
        StoreManagerInterface $storeManager = null
    ) {
        $this->contactsConfig = $contactsConfig;
        $this->transportBuilder = $transportBuilder;
        $this->inlineTranslation = $inlineTranslation;
        $this->storeManager = $storeManager ?: ObjectManager::getInstance()->get(StoreManagerInterface::class);
    }

    /**
     * Send email from contact form
     *
     * @param string $replyTo
     * @param array $variables
     * @return void
     */
    public function send($recipient, $replyTo, array $variables)
    {
        /** @see \Magento\Contact\Controller\Index\Post::validatedParams() */
        $replyToName = !empty($variables['data']['name']) ? $variables['data']['name'] : null;

        if ($recipient == 'General feedback'){
        $emails = ['aaa@gmail.com' , 'bbb@gmail.com'];  // add your email list
        }else if ($recipient == 'Warranty'){
        $emails = ['ccc@gmail.com' , 'ddd@gmail.com'];  // add your email list 
        }

        $this->inlineTranslation->suspend();
        try {
            $transport = $this->transportBuilder
                ->setTemplateIdentifier($this->contactsConfig->emailTemplate())
                ->setTemplateOptions(
                    [
                        'area' => Area::AREA_FRONTEND,
                        'store' => $this->storeManager->getStore()->getId()
                    ]
                )
                ->setTemplateVars($variables)
                ->setFrom($emails)
                //->setFrom($this->contactsConfig->emailSender())
                ->addTo($this->contactsConfig->emailRecipient())
                ->setReplyTo($replyTo, $replyToName)
                ->getTransport();

            $transport->sendMessage();
        } finally {
            $this->inlineTranslation->resume();
        }
    }
}
  • 1
    Yes you can get post params in post controller and set recipients according to you selection – Prathap Gunasekaran Mar 13 at 10:55
  • I have tried it, but not able to achieve my target. – Amy Mar 13 at 10:58
  • Hey is seems like your file isn't overridden properly. so make it working in vendor first then comes to override things to get it done @Amy – Prathap Gunasekaran Mar 14 at 8:50
  • Okay I will check – Amy Mar 14 at 8:51
  • Disable your module and do it in vendor @Amy – Prathap Gunasekaran Mar 14 at 8:52
0

Try this,

Override post controller from the below path

vendor/magento/module-contact/Controller/Index/Post.php

change the sendEmail funtion to below code

private function sendEmail($post)
{
    $this->mail->send(
        $post['select_input_name'], 
        $post['email'],
        ['data' => new DataObject($post)]
    );
}

NOTE : $post['select_input_name'] select_input_name should be your input name.

then change override Mail.php from the below path

vendor/magento/module-contact/Model/Mail.php

replace the send() to below code

public function send($recipient, $replyTo, array $variables)
{
    /** @see \Magento\Contact\Controller\Index\Post::validatedParams() */
    $replyToName = !empty($variables['data']['name']) ? $variables['data']['name'] : null;
    if ($recipient == 'option-1'){
        $emails = ['aaa@gmail.com' , 'ccc@gamil.com'];  // add your email list
    }else if ($recipient == 'option-2'){
        $emails = ['bbb@gmail.com' , 'eee@gmail.com'];  // add your email list 
    }

    $this->inlineTranslation->suspend();
    try {
        $transport = $this->transportBuilder
            ->setTemplateIdentifier($this->contactsConfig->emailTemplate())
            ->setTemplateOptions(
                [
                    'area' => Area::AREA_FRONTEND,
                    'store' => $this->storeManager->getStore()->getId()
                ]
            )
            ->setTemplateVars($variables)
            ->setFrom($this->contactsConfig->emailSender())
            ->addTo($emails)
            ->setReplyTo($replyTo, $replyToName)
            ->getTransport();

        $transport->sendMessage();
    } finally {
        $this->inlineTranslation->resume();
    }
}

Hope this helps :)

  • Thanks Prathap. I will try your answer and will let you know. – Amy Mar 13 at 12:11
  • Hi Prathap, I have tried this.. It is not working.. the email is not sending.. – Amy Mar 14 at 7:15
  • I have updated my question.. – Amy Mar 14 at 7:58
0

For an email builder I recommend you to try free the Postcards — https://designmodo.com/postcards/

This tool is the perfect combined with tools you have mentioned.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.