Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

How to Send Custom Emails in Magento 2 Programmatically

Vinh Jacker | 11-11-2024

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.

Table of content
    Jacker

    With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.



    Related Post

    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