The Most Popular Extension Builder for Magento 2

With a big catalog of 224+ extensions for your online store

How to Send Custom Emails in Magento 2 Programmatically

Since social media are creating storms in the e-commerce world, is email still a good portal to communicate with customers? Numbers say it all. In 2023, over 4.3 billions people are still using emails and the email marketing revenue reached $10.89 billion. We can see that email is still in the game and it brings back significant profits to businesses.

However, the Magento 2 default only supports limited aspects of email, such as:

  • Welcome email
  • Forgot Password email
  • Order Confirmation email
  • Invoice email
  • Shipment email
  • Credit memo email
  • Newsletter subscription email

In case you want to send a more personalized email for special occasions, the default version can not meet your requirements. Don’t worry! We will give you the solution right away.

How to Send Custom Emails in Magento 2 Programmatically

Here’s how to send custom emails in Magento 2 programmatically!

<?php

namespace [Vendor]\[Module]\Helper;

use Magento\Framework\App\Helper\Context;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Store\Model\StoreManagerInterface;

class Data extends AbstractHelper
{
    protected $transportBuilder;
    protected $storeManager;
    protected $inlineTranslation;

    public function __construct(
        Context $context,
        TransportBuilder $transportBuilder,
        StoreManagerInterface $storeManager,
        StateInterface $state
    )
    {
        $this->transportBuilder = $transportBuilder;
        $this->storeManager = $storeManager;
        $this->inlineTranslation = $state;
        parent::__construct($context);
    }

    public function sendEmail()
    {
        // this is an example and you can change template id,fromEmail,toEmail,etc as per your need.
        $templateId = 'my_custom_email_template'; // template id
        $fromEmail = '[email protected]';  // sender Email id
        $fromName = 'Admin';             // sender Name
        $toEmail = '[email protected]'; // receiver email id

        try {
            // template variables pass here
            $templateVars = [
                'msg' => 'test',
                'msg1' => 'test1'
            ];

            $storeId = $this->storeManager->getStore()->getId();

            $from = ['email' => $fromEmail, 'name' => $fromName];
            $this->inlineTranslation->suspend();

            $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
            $templateOptions = [
                'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                'store' => $storeId
            ];
            $transport = $this->transportBuilder->setTemplateIdentifier($templateId, $storeScope)
                ->setTemplateOptions($templateOptions)
                ->setTemplateVars($templateVars)
                ->setFrom($from)
                ->addTo($toEmail)
                ->getTransport();
            $transport->sendMessage();
            $this->inlineTranslation->resume();
        } catch (\Exception $e) {
            $this->_logger->info($e->getMessage());
        }
    }
}

Note: Please pay attention that the solution given above works best for Magento 2.2.x and 2.3.x versions.

Conclusion

Hope that our blog has given a bit more confidence to those who are unsure whether to implement email marketing. If you have any questions, please feel free to contact us.

Image Description
Hello, I'm the Chief Technology Officer of Mageplaza, and I am thrilled to share my story with you. My deep love and passion for technology have fueled my journey as a professional coder and an ultra-marathon runner. Over the past decade, I have accumulated extensive experience and honed my expertise in PHP development.
Website Support
& Maintenance Services

Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.

Get Started
mageplaza services
x
    Subscribe

    Stay in the know

    Get special offers on the latest news from Mageplaza.

    Earn $10 in reward now!

    Earn $10 in reward now!

    comment
    iphone
    go up