How to Send Custom Emails in Magento 2 Programmatically

How to Send Custom Emails in Magento 2 Programmatically

If you're running an online store with Magento 2, you know how important it is to communicate with your clients. Whether it's commande confirmations, shipping updates, or promotional e-mails, sending the right message at the right time can make a big difference. But what if you want to send custom e-mails that aren't covered by Magento's default e-mail templates? That's where programmatic e-mail sending comes in.

Dans cet article, nous'll walk you through comment send custom e-mails in Magento 2 programmatically. Nous allons cover everything from setting up your e-mail template to writing the code that sends the e-mail. By the end, you'll be able to send custom e-mails tailored to your specific needs.

Why Send Custom Emails Programmatically?

Magento 2 comes with a variety of built-in e-mail templates for common scenarios like commande confirmations, expédition notifications, and password resets. Cependant, there are times when you need to send e-mails that go beyond these templates. Par exemple, you might want to send a personalized thank-you e-mail after a client makes their first purchase, or notify your team when a high-valeur commande is placed.

By sending custom e-mails programmatically, you can:

  • Create highly personalized messages.
  • Trigger e-mails basé sur specific events or conditions.
  • Integrate with tiers services or APIs.
  • Automate repetitive tasks, saving you time and effort.

Step 1: Create a Custom Email Template

Avant you can send a custom e-mail, you need to create an e-mail template. Magento 2 vous permet de create and manage e-mail templates from the panneau d'administration. Voici comment:

  1. Log in to your Magento 2 panneau d'administration.
  2. Navigate to Marketing > Communications > Email Templates.
  3. Click on Add New Template.
  4. Select a template to start from (or choose "Custom Template" if you want to start à partir de zéro).
  5. Fill in the template details, including the template name, subject, and contenu.
  6. Use Magento's template variables to dynamically insert data like client names, commande numbers, or product details.
  7. Save the template.

Par exemple, here's a simple e-mail template:


<p>Hello {{var customer_name}},</p>
<p>Thank you for your recent purchase! Your order number is {{var order_number}}.</p>
<p>We hope you enjoy your new items.</p>
<p>Best regards,</p>
<p>The {{var store_name}} Team</p>

Une fois you've created your template, note down its Template Identifier. You'll need this in the next étape.

Step 2: Write the Code to Send the Email

Now that you have your e-mail template, it's time to write the code that sends the e-mail. Magento 2 provides a robust e-mail framework that you can use to send e-mails programmatically. Voici comment to do it:

  1. Create a custom module (if you don't already have one).
  2. In your module, create a new PHP fichier to handle the e-mail sending logic.
  3. Use Magento's TransportBuilder class to build and send the e-mail.

Here's an exemple of comment send a custom e-mail:


<?php

namespace Vendor\Module\Controller\Index;

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

class SendEmail extends Action
{
    protected $transportBuilder;
    protected $inlineTranslation;
    protected $storeManager;

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

    public function execute()
    {
        // Disable inline translation to avoid issues with email templates
        $this->inlineTranslation->suspend();

        try {
            // Set the template variables
            $templateVars = [
                'customer_name' => 'John Doe',
                'order_number' => '123456',
                'store_name' => 'My Store'
            ];

            // Set the sender and recipient
            $sender = [
                'name' => 'My Store',
                'email' => 'noreply@mystore.com'
            ];
            $recipient = 'customer@example.com';

            // Build the email
            $transport = $this->transportBuilder
                ->setTemplateIdentifier('your_template_identifier') // Template ID
                ->setTemplateOptions([
                    'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                    'store' => $this->storeManager->getStore()->getId()
                ])
                ->setTemplateVars($templateVars)
                ->setFrom($sender)
                ->addTo($recipient)
                ->getTransport();

            // Send the email
            $transport->sendMessage();

            // Re-enable inline translation
            $this->inlineTranslation->resume();

            echo 'Email sent successfully!';
        } catch (\Exception $e) {
            echo 'Error: ' . $e->getMessage();
        }
    }
}

In this exemple, we're using the TransportBuilder class to build and send the e-mail. The setTemplateIdentifier méthode specifies the e-mail template to use, while setTemplateVars sets the variables that sera replaced in the template.

Step 3: Trigger the Email

Now that you have the code to send the e-mail, you need to decide when and où trigger it. Voici a few common scenarios:

  • Après a client places an commande: Vous pouvez use an observateur to trigger the e-mail after the checkout_submit_all_after event.
  • When a new client registers: Use the customer_register_success event to send a welcome e-mail.
  • When a product goes on sale: Create a tâche cron to check for prix changes and send an e-mail to interested clients.

Here's an exemple of comment trigger the e-mail using an observateur:


<?php

namespace Vendor\Module\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Vendor\Module\Controller\Index\SendEmail;

class SendCustomEmail implements ObserverInterface
{
    protected $sendEmail;

    public function __construct(SendEmail $sendEmail)
    {
        $this->sendEmail = $sendEmail;
    }

    public function execute(Observer $observer)
    {
        // Trigger the email sending logic
        $this->sendEmail->execute();
    }
}

N'oubliez pas de register your observateur in your module's events.xml fichier:


<?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_submit_all_after">
        <observer name="send_custom_email" instance="Vendor\Module\Observer\SendCustomEmail"/>
    </event>
</config>

Step 4: Test Your Custom Email

Avant déployering your custom e-mail fonctionality, it's important to test it thoroughly. Voici comment:

  1. Place a test commande or trigger the event that should send the e-mail.
  2. Check your e-mail inbox (or the recipient's inbox) to ensure the e-mail is sent correctly.
  3. Verify that all template variables are replaced with the correct data.
  4. Test different scenarios, tel que invalid e-mail addresses or missing template variables, to ensure your code handles erreurs gracefully.

Conclusion

Sending custom e-mails in Magento 2 programmatically is a powerful way to enhance your store's communication capabilities. By creating custom e-mail templates and using Magento's e-mail framework, you can send personalized, event-driven e-mails that meet your specific needs. Whether you're thanking clients for their commandes, notifying your team about important events, or promoting new products, custom e-mails can help you build stronger relationships with your audience.

If you're looking for a reliable hosting solution to support your Magento 2 store, check out Magefine. We offer optimized Magento hosting plans that ensure your store runs smoothly and efficiently.

Happy coding!