0

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="My\Module\Observer\SendEmailForCart"/>
</event>

My/Module/Observer/SendEmailForCart.php

<?php
namespace My\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use My\Module\Helper\Email;

class SendEmailForCart implements ObserverInterface
{
    private $helperEmail;

    public function __construct(
        Email $helperEmail
    ) {
        $this->helperEmail = $helperEmail;
    }
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        return $this->helperEmail->sendEmail();
    }
}

My/Module/Helper/Email.php

<?php

namespace My\Module\Helper;

class Email extends \Magento\Framework\App\Helper\AbstractHelper
{

    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?

2 Answers 2

0

Basic Code for sending email is this one :

use Magento\Framework\Event\ObserverInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Translate\Inline\StateInterface;

class ClassName implements ObserverInterface
{
   protected $storeManager;
   protected $_transportBuilder;
   protected $inlineTranslation;

   public function __construct(StoreManagerInterface $smi,TransportBuilder $tb,StateInterface $si)
   {        
       $this->storeManager=$smi;
       $this->_transportBuilder=$tb;
       $this->inlineTranslation=$si;
   }

   public function yourFunctionName()
   {
       $templateOptions = array('area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => $this->storeManager->getStore()->getId());
        $templateVars = array(
            'store' => $this->storeManager->getStore(),
            'customer_name' => $cname,
            'message'   => 'YOUR MESSAGE TEXT'
        );
        $from = array('email' => "SENDEREMAILADDRESS", 'name' => 'SENDERNAME');
        $this->inlineTranslation->suspend();
        $to = array('RECEIVEREMAILADDRESS');
        $transport = $this->_transportBuilder->setTemplateIdentifier('order_template')
            ->setTemplateOptions($templateOptions)
            ->setTemplateVars($templateVars)
            ->setFrom($from)
            ->addTo($to)
            ->getTransport();
        $transport->sendMessage();
        $this->inlineTranslation->resume();
   } 
}

NOTE : we use order_template in the above code for the testing. you need to repalce that with your real template.

0

In the Email.php file, you need to implement the logic for sending the email.

<?php
 namespace My\Module\Helper;

 use Magento\Framework\Mail\Template\TransportBuilder;
 use Magento\Framework\App\Helper\AbstractHelper;
 use Magento\Framework\App\Helper\Context;
 use Magento\Framework\Escaper;
 use Magento\Store\Model\StoreManagerInterface;

class Email extends AbstractHelper
{
    protected $_transportBuilder;
    protected $_escaper;
    protected $_storeManager;

   public function __construct(
      Context $context,
      TransportBuilder $transportBuilder,
      Escaper $escaper,
      StoreManagerInterface $storeManager
   ) {
    parent::__construct($context);
    $this->_transportBuilder = $transportBuilder;
    $this->_escaper = $escaper;
    $this->_storeManager = $storeManager;
}

public function sendEmail()
{
    $sender = [
        'name' => $this->_escaper->escapeHtml('Sender Name'),
        'email' => '[email protected]'
    ];

    $recipientEmail = '[email protected]';
    $recipientName = 'Recipient Name';

    $transport = $this->_transportBuilder
        ->setTemplateIdentifier('my_email_template') // Change this to your email template ID
        ->setTemplateOptions(['area' => 'frontend', 'store' => $this->_storeManager->getStore()->getId()])
        ->setTemplateVars(['data' => 'Additional Data']) // Add any additional data you want to pass to the email template
        ->setFrom($sender)
        ->addTo($recipientEmail, $recipientName)
        ->getTransport();

    try {
        $transport->sendMessage();
    } catch (\Exception $e) {
        // Handle exception
    }
}
}

Make sure to replace Sender Name, [email protected], [email protected], and Recipient Name with appropriate values. Also, replace my_email_template with the ID of your email template.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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