Send mail from custom module Magento 2

To send custom email in Magento 2 using the module, We need to create a custom module to send email to a specific recipient.

There are many default Magento mail template are available like Sales Order, Customer mails, Contacts and so on. if you want to send your custom mail functionality using Magento 2, You need to create a simple module and create custom template file using Module for mail body.

You need to create first registration.php and module.xml file for defining our module. Here I have used Rbj as Packagename where SendEmail is a module name.

Check Image Attachment with Email by link, Image Attachment with Email Template Magento 2

Path: app/code/Rbj/SendEmail/registration.php

Create module.xml file, Path: app/code/Rbj/SendEmail/etc/module.xml

For Create custom email templates in Module, We need to create an email_templates.xml file for defining our template file plus an area of mail sending whether its frontend or adminhtml area. Type is HTML or text will be defined in below XML file. file attribute is for our custom file.

Path: app/code/Rbj/SendEmail/etc/email_templates.xml

We need to create a system.xml file for set default email template settings.
Path: app/code/Rbj/SendEmail/etc/adminhtml/system.xml

In an above system.xml file, we have to define email Module is enable or not, Default sender of an email and default email template to send with email body.

Create a config.xml file set default sender data and email template to send when email is fired.
Path: app/code/Rbj/SendEmail/etc/config.xml

We have set default setting enabled equals to 1 for enable module.
sender value as general.

For general default, email id takes from a backend.
Stores -> General -> Store Email Address -> General Contact.
Sender name and sender email will be taken.
email_template is our custom email template which we have defined under view/frontend folder below.

Now we will define our custom email template for send body of the mail.
Path: app/code/Rbj/SendEmail/view/frontend/email/email_file.html

You can modify the above file based on your requirement.

Now Main logic for send email resides under Helper file.

Magento\Framework\Mail\Template\TransportBuilder is used for sending custom email in Magento 2. TransportBuilder class has the ability to send custom email based on your requirement. You need to pass all the required field in TransportBuilder class function.

Path: app/code/Rbj/SendEmail/Helper/Data.php

Here we have defined an area as frontend \Magento\Framework\App\Area::AREA_FRONTEND
$email is your receiver email id.
if you want to send multiple email address, pass email id as an array in addBcc() method.

  • Send email using below function in your template or block file.

$this->helper(‘Rbj\SendEmail\Helper\Data’)->sendTransactionalEmail();