How to Send Custom Emails Programmatically in Magento 2
Emails are a traditional but effective way of communication for business. According to Hubspot, active Email accounts are expected to hit 5.6 billion by 2019.
This clearly shows that when there are more platforms to communicate with the audience than ever before, the Email is still a popular platform.
The Magento 2 store owners can make the most out of it by sending various types of Emails such as
- Acknowledgment Emails
- Marketing Emails
- Transactional Emails
- Newsletters/Informative Emails
- Milestone Emails
- Plain text Emails
- Lead Nurturing Emails
However, the default Magento 2 does not support such a wide variety of Emails. It only supports:
- Welcome Email
- Forgot Password Email
- Order Confirmation Email
- Invoice Email
- Shipment Email
- Credit Memo Email
- Newsletter subscription Email
However, when you want to send personalized emails like offers, birthday wishes to customers, etc, you can use the method given here to send custom Emails programmatically in Magento 2.
Steps to Send Custom Emails Programmatically in Magento 2:
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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
<?php namespace [Vendor]\[Module]\Helper; use Magento\Framework\App\Helper\Context; use Magento\Framework\Mail\Template\TransportBuilder; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\Translate\Inline\StateInterface; use Magento\Store\Model\StoreManagerInterface; class Data extends AbstractHelper { protected $transportBuilder; protected $storeManager; protected $inlineTranslation; public function __construct( Context $context, TransportBuilder $transportBuilder, StoreManagerInterface $storeManager, StateInterface $state ) { $this->transportBuilder = $transportBuilder; $this->storeManager = $storeManager; $this->inlineTranslation = $state; parent::__construct($context); } public function sendEmail() { // this is an example and you can change template id,fromEmail,toEmail,etc as per your need. $templateId = 'my_custom_email_template'; // template id $fromName = 'Admin'; // sender Name try { // template variables pass here $templateVars = [ 'msg' => 'test', 'msg1' => 'test1' ]; $storeId = $this->storeManager->getStore()->getId(); $from = ['email' => $fromEmail, 'name' => $fromName]; $this->inlineTranslation->suspend(); $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; $templateOptions = [ 'area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => $storeId ]; $transport = $this->transportBuilder->setTemplateIdentifier($templateId, $storeScope) ->setTemplateOptions($templateOptions) ->setTemplateVars($templateVars) ->setFrom($from) ->addTo($toEmail) ->getTransport(); $transport->sendMessage(); $this->inlineTranslation->resume(); } catch (\Exception $e) { $this->_logger->info($e->getMessage()); } } } |
Note: The above solution is for the Magento 2.2.x and Magento 2.3.x versions.
Here’s another useful solution to add birthday field to checkout in Magento 2, which you can use to collect birthday information from customers for sending wishes.
Take the maximum benefit of emails by sending custom emails that you can think of using this method!
If you face any doubts in the implementation, let me in the Comments section below. I’d be happy to help.
Feel free to share the solution with fellow developers on social media.
Thank you.
📧 Keep Emailing! 📧
Still need help? Hire our Adobe-certified Magento experts.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
18 Comments
Hi,
The above code is working with Magento 2.4.3
However, the email is not getting the values assigned in setTemplateVars. Only static content in my template is getting in my email content.
Hello John,
Please be informed that the above solution is for the Magento 2.2.x and Magento 2.3.x versions.
Thank You
Hi
How we can use the extension i am confuse little bit
i want to use that script like that (php -f test.php)
Please tell me how we can run the script
Hello Moazzam,
Please create test.php root script and add code to root script
For reference : https://meetanshi.com/blog/create-root-script-in-magento-2/
Thank you
Hey dear Sanjy,
Can I do Above in plugin? without creating any helper? actually I’m facing o send reset email from custom module and area is admin not frontend
Thanks in advance
Hello Zahid,
Yes, you can use the code for send mail wherever you need.
Thank You
How to add attachment with mail?
Please follow the solution at https://meetanshi.com/blog/add-attachments-with-email-in-magento-2-3-x/
Hi,
I am using the Magento 2.2.5 version and I am confused where to add this code file.
What is the path for this file to run the script.
And what about the namespace [Vendor]\[Module]\Helper; in above code given. What is the [Vendor] and [Module], please help me asap.
Thanks and Regards,
Hello Kamal,
The above code is just an example and hence I’ve used the path Vendor/Module/.
You have to use this code file in an already existing module. You’ll find a file name Helper/Data.php file and public function sendEmail() { } and other variables which are to be used.
If you are developing a custom module in Magento 2, refer here.
Thank you.
Hi,
We have a registry and followed the steps you mentioned, but still after creating the registry. Customer is not receiving the email.
Thank you,
April
Hey, Please check the updated code.
Thanks.
Hi,
I am using Magento 2.3.3 version and getting below error:
Type Error occurred when creating object: Magento\Framework\Mail\EmailMessage\Interceptor
Below is my code. What I am doing wrong here?
$this->transportBuilder
->setTemplateIdentifier($templateId)
->setTemplateOptions([
‘area’ => \Magento\Framework\App\Area::AREA_FRONTEND,
‘store’ => $this->storeManager->getStore()->getId(),
])
->setFrom($sender)
->setTemplateVars([
‘data’ => $myData
])
->addTo($recipient);
if (!empty($bcc)) {
$this->transportBuilder->addBcc($bcc);
}
$this->transportBuilder->getTransport()->sendMessage();
Hey Suhas, please check the updated solution.
Thank you.
hey..can you please share code for version 2.4.2
Hello Sanjay,
The above code is working for Magento 2.4.2.
Thank You.
Did you try adding accent to the sender email ? like “Fácil” is not working for me, i got “Invalid header value detected” but if i remove the accent “á” it send the email
Hello Davinson,
Which Magento version you are using?
There’s an issue related to encoding/serialize in Magento 2.3.3 version.
Please refer here: https://github.com/magepal/magento2-gmail-smtp-app/issues/152
Thank You.