How to Send Magento 2 Order Confirmation Email After Payment Success

by mageefy on Jan 3, 2023 Celebrities 364 Views

Default Magento automatically sends an order confirmation email once the order is placed. But what if someone wants to send an email after a successful payment completion from the third-party payment gateways in Magento 2 or what if the card is declined and payment fails? Unfortunately, Default Magento does not provide the functionality of sending email after getting successful payment from third-party gateways so we have come up with a custom code to send Email manually using event observer.

If you want to send the email only after the successful payment then you must write code in observer for checkout_onepage_controller_success_action event.

 

Create a simple method isEnable() using OrderIdentity.php to ensure that the order confirmation email is not sent twice.

Register the event under events.xml using the below code

[Package_Name]\[Module_Name]\etc\frontend\events.xml

 

<?xml version="1.0"?>

 

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

    <event name="checkout_onepage_controller_success_action">

        <observer name="checkout_onepage_controller_success_action_sendmail" instance="[Package_Name]\[Module_Name]\Observer\SendMailOnOrderSuccess" />

    </event>

</config>

Once the event is registered, create Observer class in the following file:

[Package_Name]\[Module_Name]\Observer\SendMailOnOrderSuccess.php

 

 

 

<?php

 

namespace [Package_Name]\[Module_Name]\Observer;

 

use Magento\Framework\Event\ObserverInterface;

 

class SendMailOnOrderSuccess implements ObserverInterface

{

    /**

     * @var \Magento\Sales\Model\OrderFactory

     */

    protected $orderModel;

 

    /**

     * @var \Magento\Sales\Model\Order\Email\Sender\OrderSender

     */

    protected $orderSender;

 

    /**

     * @var \Magento\Checkout\Model\Session $checkoutSession

     */

    protected $checkoutSession;

 

    /**

     * @param \Magento\Sales\Model\OrderFactory $orderModel

     * @param \Magento\Sales\Model\Order\Email\Sender\OrderSender $orderSender

     * @param \Magento\Checkout\Model\Session $checkoutSession

     *

     * @codeCoverageIgnore

     */

    public function __construct(

        \Magento\Sales\Model\OrderFactory $orderModel,

        \Magento\Sales\Model\Order\Email\Sender\OrderSender $orderSender,

        \Magento\Checkout\Model\Session $checkoutSession

    )

    {

        $this->orderModel = $orderModel;

        $this->orderSender = $orderSender;

        $this->checkoutSession = $checkoutSession;

    }

 

    /**

     * @param \Magento\Framework\Event\Observer $observer

     * @return void

     */

    public function execute(\Magento\Framework\Event\Observer $observer)

    {

        $orderIds = $observer->getEvent()->getOrderIds();

        if(count($orderIds))

        {

            $this->checkoutSession->setForceOrderMailSentOnSuccess(true);

            $order = $this->orderModel->create()->load($orderIds[0]);

            $this->orderSender->send($order, true);

        }

    }

}

 

 

After adding observer code, an email will be sent to customers on successful order payment. To avoid order duplication Email, we need to create a plugin using the di.xml file.

[Package_Name]\[Module_Name]\etc\di.xml

 

<?xml version="1.0"?>

 

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <type name="Magento\Sales\Model\Order\Email\Container\OrderIdentity">

        <plugin name="change_is_enable_method" type="\[Package_Name]\[Module_Name]\Plugin\Sales\Order\Email\Container\OrderIdentityPlugin"/>

    </type>

</config>

 

 

And Lastly, you need to create another file along with ‘di.xml’ that is OrderIdentityPlugin.php to remove duplication of email.

[Package_Name]\[Module_Name]\Plugin\Sales\Order\Email\Container\ OrderIdentityPlugin.php

 

 

 

<?php

 

namespace [Package_Name]\[Module_Name]\Plugin\Sales\Order\Email\Container;

 

class OrderIdentityPlugin

{

    /**

     * @var \Magento\Checkout\Model\Session $checkoutSession

     */

    protected $checkoutSession;

 

    /**

     * @param \Magento\Checkout\Model\Session $checkoutSession

     *

     * @codeCoverageIgnore

     */

    public function __construct(

        \Magento\Checkout\Model\Session $checkoutSession

    )

    {

        $this->checkoutSession = $checkoutSession;

    }

 

    /**

     * @param \Magento\Sales\Model\Order\Email\Container\OrderIdentity $subject

     * @param callable $proceed

     * @return bool

     */

    public function aroundIsEnabled(\Magento\Sales\Model\Order\Email\Container\OrderIdentity $subject, callable $proceed)

    {

        $returnValue = $proceed();

 

        $forceOrderMailSentOnSuccess = $this->checkoutSession->getForceOrderMailSentOnSuccess();

        if(isset($forceOrderMailSentOnSuccess) && $forceOrderMailSentOnSuccess)

        {

            if($returnValue)

                $returnValue = false;

            else

                $returnValue = true;

 

            $this->checkoutSession->unsForceOrderMailSentOnSuccess();

        }

 

        return $returnValue;

    }

}

That’s it! Now start sending the order confirmation Emails to your customers only after the payment is successful! Hope this code will help you to send Order Confirmation Email to your Customers after Successful Payment Transaction. You can even use & customize this code according to your need.

 

Related Best Magento Extension for your eCommerce Business- 

 

Bundle Product Option Image Extension For Magento 2

 

Reindex from Backend for Magento 2 Extension

 

Contact Us Inquiry Manager for Magento 2

 

Contact- 

 

Email  -  support@mageefy.com

              mageefy@gmail.com

 

Visit -  https://www.mageefy.com/

 

Address -  72, Second Floor, Ganesh Vihar Extension, Sirsi Road, Jaipur - 302034, India.

(+91) 0141- 6693741

 

 

 

 

Article source: https://article-realm.com/article/Arts-Entertainment/Celebrities/34450-How-to-Send-Magento-2-Order-Confirmation-Email-After-Payment-Success.html

Comments

No comments have been left here yet. Be the first who will do it.
Safety

captchaPlease input letters you see on the image.
Click on image to redraw.

Reviews

Guest

Overall Rating:

Most Viewed Articles

Statistics

Members
Members: 16703
Publishing
Articles: 78,338
Categories: 202
Online
Active Users: 186
Members: 12
Guests: 174
Bots: 3688
Visits last 24h (live): 1268
Visits last 24h (bots): 41596

Latest Comments

The feedback mechanism following Peeragarhi Escort bookings helps improve the service quality, though this occurs after the experience rather than during the booking phase itself.  
확실히 그것의 모든 조금을 즐기십시오. 그리고 나는 당신의 블로그의 새로운 내용을 확인하기 위해 당신이 즐겨 찾기에 추가했습니다. 반드시 읽어야 할 블로그입니다!  업토토  
이 멋진 정보를 얻게되어 정말 감사합니다  지니토토    
체중 감량에 성공하려면 외모 이상에 집중해야합니다. 기분, 전반적인 건강 및 정신 건강을 활용하는 접근 방식이 가장 효율적입니다. 두 가지 체중 감량 여정이 똑같지 않기 때문에 대대적 인 체중 감량을 달성 한 많은 여성에게 정확히 어떻게했는지 물었습니다.  네임드 도메인 주소    
" '훌륭한 유용한 리소스를 무료로 제공하는 가격을 알 수있는 웹 사이트를 보는 것이 좋습니다. 귀하의 게시물을 읽는 것이 정말 마음에 들었습니다. 감사합니다! 훌륭한 읽기, 긍정적 인 사이트,이 게시물에 대한 정보를 어디서 얻었습니까? 지금 귀하의 웹 사이트에서 몇 가지 기사를 읽었으며 귀하의 스타일이 정말 마음에 듭니다. 백만명에게 감사하고...
This "blogging" example just looks like a list of unrelated website login prompts and tech support links. It's really confusing; I was expecting actual thoughts or advice on blogging, not a random...
on Jul 16, 2026 about Blogging
This article has some really thoughtful points about unconditional love in a relationship, especially the emphasis on honesty and acceptance. It's refreshing to see these qualities highlighted as...
Great article! It's fascinating to learn about the rich history and unique experience of the Darjeeling Himalayan Railway. Well-written and informative. As a pitch deck design agency , we...
This content effectively details welfare programs in Andhra Pradesh. Chandrababu Naidu's initiatives are clearly outlined, demonstrating a focus on community and transparency. Just like a player...
That's a really insightful post about picking the right web design company! It truly highlights how crucial it is to align the design with your business model. I especially resonate with the point...

Translate To: