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:
Create new html file
/app/code/VendorName/ModuleName/view/frontend/email/modulename/test.html
with simple content:
1 2 3 4 5 |
<div> Hello, this is a test email. </div> |
Declare your email template, create xml file
/app/code/VendorName/ModuleName/etc/email_templates.xml
with content:
1 2 3 4 5 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:Magento:module:Magento_Email:etc/email_templates.xsd"> <template id="modulename_test_template" label="Test email" file="modulename/test.html" type="html" module="VendorName_ModuleName" area="frontend"/> </config> |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
<?php namespace VendorName\ModuleName\Controller; use Magento\Framework\App\RequestInterface; class Sendemail extends \Magento\Framework\App\Action\Action { /** * @var \Magento\Framework\App\Request\Http */ protected $_request; /** * @var \Magento\Framework\Mail\Template\TransportBuilder */ protected $_transportBuilder; /** * @var \Magento\Store\Model\StoreManagerInterface */ protected $_storeManager; public function __construct( \Magento\Framework\App\Action\Context $context , \Magento\Framework\App\Request\Http $request , \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder , \Magento\Store\Model\StoreManagerInterface $storeManager ) { $this->_request = $request; $this->_transportBuilder = $transportBuilder; $this->_storeManager = $storeManager; parent::__construct($context); } public function execute() { $store = $this->_storeManager->getStore()->getId(); $transport = $this->_transportBuilder->setTemplateIdentifier('modulename_test_template') ->setTemplateOptions(['area' => 'frontend', 'store' => $store]) ->setTemplateVars( [ 'store' => $this->_storeManager->getStore(), ] ) ->setFrom('general') // you can config general email address in Store -> Configuration -> General -> Store Email Addresses ->getTransport(); $transport->sendMessage(); return $this; } } |
You also can create this function in helper, model …
If you have any question, just leave a comment or contact us.
Thanks.