Magento 2 send email programmatically

Magento 2 send email programmatically – In this post, let’s find out how to send email programmatically in Magento 2. It will be useful for you in your custom module or new feature. What we need to do:

  • Create your email template in a html file.
  • Declare your email template.
  • Create a function to send your email.

We’re doing step by step:

1. Create new html file

/app/code/VendorName/ModuleName/view/frontend/email/modulename/test.html

with simple content:

2. Declare your email template, create xml file

/app/code/VendorName/ModuleName/etc/email_templates.xml

with content:

3. Finally, create a function to send your email.

In this tutorial, we’re using a controller action. Create file:

/app/code/VendorName/ModuleName/Controller/Index/Sendemail.php

with content:

You also can create this function in helper, model …

If you have any question, just leave a comment or contact us.

Thanks.

3 thoughts on “Magento 2 send email programmatically

  1. Hello.

    Thank you very much for posting this tutorial.
    I am a Magento 2 newbie, and I have been looking for a complete and working solution like this to send an email programmatically.

    I know that this isn’t a question and answer forum, but using the code you posted as an example, could you tell me how it might be possible to send an email from a .phtml file? I made a custom success.phtml file which works fine except for the email part, which I included in it. Since I am a newbie, I assumed that that is where I should have placed it. Should I place the Sendemail.php in the .phtml file or call it somehow? If I need to call it from the .phtml file, what command do I need to use?

    Thank you very much.

    1. I think you already declared your template file and block using a layout file.
      So you should create send email function in your block and call it using: $block->sendEmail();
      Hope this could help.

Leave a Reply

Your email address will not be published.