Skip to content
Advertisement

How to send an e-mail after adding the product to the cart in magento 2?

Unfortunately, so far I am a complete beginner in creating a module in magento. I need to send an email after adding the item to the cart.

As I understand it, I need to use the checkout_cart_product_add_after event

I created some files, but I don’t understand how to send an email after adding the item to the cart

My/Module/etc/events.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="checkout_cart_product_add_after">
    <observer name="email_after_adding_product" instance="MyModuleObserverSendEmailForCart"/>
</event>

My/Module/Observer/SendEmailForCart.php

<?php
namespace MyModuleObserver;

use MagentoFrameworkEventObserverInterface;
use MyModuleHelperEmail;

class SendEmailForCart implements ObserverInterface
{
    private $helperEmail;

    public function __construct(
        Email $helperEmail
    ) {
        $this->helperEmail = $helperEmail;
    }
    public function execute(MagentoFrameworkEventObserver $observer)
    {
        return $this->helperEmail->sendEmail();
    }
}

My/Module/Helper/Email.php

<?php

namespace MyModuleHelper;

class Email extends MagentoFrameworkAppHelperAbstractHelper
{

    public function __construct(

    )
    {

    }

    public function sendEmail()
    {
        try {
            
        } catch (Exception $e) {

        }
    }
}

Please tell, what code I need to write in the Email.php file? And do I need to create any additional files or modify the ones I showed above?

Advertisement

Answer

/**
* Recipient email config path
*/
const XML_PATH_EMAIL_RECIPIENT = 'contact/email/recipient_email';
/**
* @var MagentoFrameworkMailTemplateTransportBuilder
*/
protected $_transportBuilder;

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

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

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

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

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

    $this->inlineTranslation->suspend();

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

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

        $storeScope = MagentoStoreModelScopeInterface::SCOPE_STORE; 
        $transport = $this->_transportBuilder
            ->setTemplateIdentifier('send_email_email_template') // 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' => MagentoStoreModelStore::DEFAULT_STORE_ID,
                ]
            )
            ->setTemplateVars(['data' => $postObject])
            ->setFrom($sender)
            ->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_RECIPIENT, $storeScope))
            ->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.')
            );
            $this->_redirect('*/*/');
            return;
    } catch (Exception $e) {
        $this->inlineTranslation->resume();
        $this->messageManager->addError(__('We can't process your request right now. Sorry, that's all we know.'.$e->getMessage())
        );
        $this->_redirect('*/*/');
        return;
    }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement