How to send custom mail in magento 2

In Magento 2, you can send custom emails using the Magento\Framework\Mail\Template class. Here's a step-by-step guide on how to send a custom email:

Step 1: Create a new email template

Create a new file in the app/code/Vendor/Module/view/frontend/email directory (replace Vendor and Module with your module's namespace and name). For example, myemail.phtml.

In this file, add your email template HTML code. You can use Magento's email template syntax, such as {{var name}} to insert variables.

Step 2: Create a new email template variable

In your email template file, add a variable that will hold the data you want to send in the email. For example, {{var customerName}}.

Step 3: Create a new email template translation

Create a new file in the app/code/Vendor/Module/view/frontend/email/email_template directory (replace Vendor and Module with your module's namespace and name). For example, myemail_template.xml.

In this file, add the translation for your email template. For example:

<?xml version="1.0"?>
<email_template>
    <template>myemail.phtml</template>
    <variables>
        <customerName>{{var customerName}}</customerName>
    </variables>
</email_template>

Step 4: Create a new email template configuration

Create a new file in the app/code/Vendor/Module/etc/email_templates directory (replace Vendor and Module with your module's namespace and name). For example, myemail_template.xml.

In this file, add the configuration for your email template. For example:

<?xml version="1.0"?>
<email_templates>
    <myemail_template>
        <template>myemail.phtml</template>
        <variables>
            <customerName>{{var customerName}}</customerName>
        </variables>
    </myemail_template>
</email_templates>

Step 5: Send the custom email

In your module's code, use the Magento\Framework\Mail\Template class to send the custom email. For example:

use Magento\Framework\Mail\Template;
use Magento\Framework\Mail\TemplateVariables;

// Get the template variables
$templateVariables = new TemplateVariables();
$templateVariables->addData([
    'customerName' => 'John Doe',
]);

// Get the template
$template = new Template('myemail_template');

// Send the email
$template->send($templateVariables);

In this example, we create a new TemplateVariables object and add the customerName variable to it. We then create a new Template object and pass the myemail_template name to it. Finally, we call the send method on the Template object, passing the TemplateVariables object as an argument.

That's it! With these steps, you should be able to send a custom email in Magento 2.