1

I'm trying to send an email from the custom module, for that I have created a controller file, XML file and html file, below is my code

app/code/Magelearn/Customform/Controller/Index/ Save.php

<?php

namespace Magelearn\Customform\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magelearn\Customform\Model\CustomformFactory;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Magento\Framework\Image\AdapterFactory;
use Magento\Framework\Filesystem;

use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Translate\Inline\StateInterface;
use Psr\Log\LoggerInterface;
use Magento\Store\Model\StoreManagerInterface;

use Magento\Framework\App\Config\ScopeConfigInterface;

class Save extends \Magento\Framework\App\Action\Action
{
    const XML_PATH_EMAIL_RECIPIENT_NAME = 'trans_email/ident_support/name';
    const XML_PATH_EMAIL_RECIPIENT_EMAIL = 'trans_email/ident_support/email';

    /**
     * @var Customform
     */
    protected $_customform;
    protected $uploaderFactory;
    protected $adapterFactory;
    protected $filesystem;

    protected $_transportBuilder;
    protected $_inlineTranslation;
    protected $_logLoggerInterface;
    protected $_scopeConfig;
    protected $storeManager;

    public function __construct(
        Context $context,
        CustomformFactory $customform,
        UploaderFactory $uploaderFactory,
        AdapterFactory $adapterFactory,
        Filesystem $filesystem,

        TransportBuilder $transportBuilder,
        StateInterface $inlineTranslation,
        LoggerInterface $logLoggerInterface,    
        StoreManagerInterface $storeManager,
        ScopeConfigInterface $scopeConfig
    ) {
        $this->_customform = $customform;
        $this->uploaderFactory = $uploaderFactory;
        $this->adapterFactory = $adapterFactory;
        $this->filesystem = $filesystem;

        $this->_transportBuilder = $transportBuilder;
        $this->_inlineTranslation = $inlineTranslation;
        $this->_logLoggerInterface = $logLoggerInterface;
        $this->storeManager = $storeManager;
        $this->_scopeConfig = $scopeConfig;

        parent::__construct($context);
    }
    public function execute()
    {
        if (!$this->getRequest()->isPost()) {
            return $this->resultRedirectFactory->create()->setPath('*/*/');
        }
    try {
        //$data = $this->getRequest()->getParams();
        $data = $this->validatedParams();
        if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') {
            try{
                $uploaderFactory = $this->uploaderFactory->create(['fileId' => 'image']);
                $uploaderFactory->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
                $imageAdapter = $this->adapterFactory->create();
                $uploaderFactory->addValidateCallback('custom_image_upload',$imageAdapter,'validateUploadFile');
                $uploaderFactory->setAllowRenameFiles(true);
                $uploaderFactory->setFilesDispersion(true);
                $mediaDirectory = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA);
                $destinationPath = $mediaDirectory->getAbsolutePath('magelearn/customform');
                $result = $uploaderFactory->save($destinationPath);
                if (!$result) {
                    throw new LocalizedException(
                        __('File cannot be saved to path: $1', $destinationPath)
                    );
                }
                
                $imagePath = 'magelearn/customform'.$result['file'];
                $data['image'] = $imagePath;
            } catch (\Exception $e) {
            }
        }
        $customform = $this->_customform->create();
        $customform->setData($data);
        if($customform->save()){
            
            // Send email
            $this->sendEmail($data);

            $this->messageManager->addSuccessMessage(__('Your inquiry has been submitted successfully.'));
        }else{
            $this->messageManager->addErrorMessage(__('An error occurred while processing your request. Please try again later.'));
        }
    }catch (\Exception $e) {
            $this->messageManager->addErrorMessage(__('An error occurred while processing your request. Please try again later.'));
            $this->_logLoggerInterface->error($e->getMessage());
    }

        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setPath('customform');
        return $resultRedirect;
    }
/**
     * @return array
     * @throws \Exception
     */
    private function validatedParams()
    {
        $request = $this->getRequest();
        if (trim($request->getParam('first_name')) === '') {
            throw new LocalizedException(__('Enter the First Name and try again.'));
        }
        if (trim($request->getParam('last_name')) === '') {
            throw new LocalizedException(__('Enter the Last Name and try again.'));
        }
        if (false === \strpos($request->getParam('email'), '@')) {
            throw new LocalizedException(__('The email address is invalid. Verify the email address and try again.'));
        }
        if (trim($request->getParam('phone')) === '') {
            throw new LocalizedException(__('Enter the Phone Number and try again.'));
        }
        if (trim($request->getParam('message')) === '') {
            throw new LocalizedException(__('Enter your message and try again.'));
        }
        return $request->getParams();
    }    

    /**
     * Send email
     *
     * @param array $data
     * @return void
     */
    private function sendEmail($data)
    {
        $storeId = $this->storeManager->getStore()->getId();
        $request = $this->getRequest();
        $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
        
        $emailTemplate = 'customform_email_template'; 

        // Retrieve store Name
        $storeName = $this->_scopeConfig->getValue(
            'trans_email/ident_general/email',
            $storeScope
        );

        // Retrieve store email ID
        $storeEmail = $this->_scopeConfig->getValue(
            'trans_email/ident_general/name',
            $storeScope
        );
        
        $emailSender = [
            'name' => $storeName, 
            'email' => $storeEmail, 
        ];
        
        $emailRecipient = [
            'name' => $data['first_name'], 
            'email' => $data['email'], 
        ];
        
        $emailVars = [
            'first_name' => $data['first_name'],
            'last_name'  => $data['last_name'],
            'email'      => $data['email'],
            'phone'      => $data['phone'],
            'message'    => $data['message'],
        ];
        
        $this->_inlineTranslation->suspend();
        
        $transport = $this->_transportBuilder
            ->setTemplateIdentifier($emailTemplate,$storeScope)
            ->setTemplateOptions([
                'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                'store' => $storeId,
            ])
            ->setTemplateVars($emailVars)
            ->setFrom($emailSender)
            ->addTo($emailRecipient['email'], $emailRecipient['name'])
            ->getTransport();
            
        $transport->sendMessage();
        $this->_logLoggerInterface->debug('Email sent successfully.');

        $this->_inlineTranslation->resume();
    }    
}

app/code/Magelearn/Customform/etc/ customform_email_template.xml

<?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="customform_email_template" label="Custom Module Email Template" file="customform_email_template.html" type="html" module="Magelearn_Customform" area="frontend"/>
</config>

app/code/Magelearn/Customform/view/frontend/email customform_email_template.html

{{template config_path="design/email/header_template"}}
<h1>New Form Submission</h1>
<p>First Name: {{var first_name}}</p>
<p>Last Name: {{var last_name}}</p>
<p>Name: {{var name}}</p>
<p>Email: {{var email}}</p>
<p>Phone: {{var phone}}</p>
<p>Message: {{var message}}</p>
{{template config_path="design/email/footer_template"}}

error is :

[2023-06-21T11:28:14.220698+00:00] main.ERROR: Email template 'customform_email_template' is not defined. [] []

4
  • one time you need to check the mail send from root directory or not create on file on project root and add this php code "mail("[email protected]","My subject","message);"
    – Jay Parmar
    Jun 21, 2023 at 11:39
  • 1
    I think you need to change the file name app/code/Magelearn/Customform/etc/ customform_email_template.xml to app/code/Magelearn/Customform/etc/email_templates.xml
    – Priya
    Jun 21, 2023 at 11:42
  • @Priya ok so i need to change file name customform_email_template.xml to email_templates.xml and in controller $emailTemplate = 'customform_email_template'; need to remaning same? Jun 21, 2023 at 11:45
  • okay @Rushikesh Solanki
    – Priya
    Jun 21, 2023 at 11:53

1 Answer 1

2

Rename : From customform_email_template.xml To email_templates.xml File name.

Path : app/code/Magelearn/Customform/etc/email_templates.xml

1
  • 1
    Approve the answer if it's correct...+1 Jun 22, 2023 at 7:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.