How to send an email from a custom module in Magento 2
Hi everybody, I am Cuong, Welcome back to my Magento 2 tutorial video series.
Today, I am going to show everybody a best practice, How to send an email from a custom module in Magento 2.
In this practice, we are going to write some codes, that allows sending an email notification to the administrator whenever a customer logs into their account.
Let’s do this practice, you need to follow steps by step:
Step 1: Declaring a new module called PHPCuong_TransactionalEmail
– Create the namespace PHPCuong in the path appcode.
– Create the module named TransactionalEmail in the path appcodePHPCuong.
– Create the file named registration.php in the path appcodePHPCuongTransactionalEmail
– Create the file named module.xml in the path appcodePHPCuongTransactionalEmailetc
End of the step #1, I have been completed the step to create a new module called PHPCuong_TransactionalEmail.
Step 2: Declaring a new email template
– Create the new file email_templates.xml in the path appcodePHPCuongTransactionalEmailetc
– Create the new file customer_logged_in.html in the path appcodePHPCuongTransactionalEmailviewfrontendemail
Step 3: Declaring the new observer sends an email notification to the administrator after the customer logged in successfully.
– Create the new file named events.xml in the path appcodePHPCuongTransactionalEmailetcfrontend
You can learn about How to use events and observers in Magento 2 in the video link
Step 4: Test and See the results
Run the commands line following:
php bin/magento setup:upgrade (Install the new modules)
php bin/magento setup:static-content:deploy (Deploy the static contents)
php bin/magento cache:flush (Flush caches)
You can see the new modules installed successfully here.
Go to the customer login page.
Check the email for getting the notification
Yeah, it works perfectly.
I try to log in with another account.
I tested with the localhost so this image does not exist on the internet.
Thank you for your watching. If you have any questions about this practice please feel free to leave a comment below.
Don’t forget to like, comment, share and subscribe to my channel for getting the latest videos.
Please do not hesitate to contact me if you need me to join your Magento project. My rate is $25/hour in Magento 1 and $30/hour in Magento 2.
Get the source code of this practice in the Github