0

I have created a custom email template. I'm using transport builder to send the email, but for some strange reason the email is empty. To send email I'm using mageplaza-magento-2-smtp extension. Below my code:

etc/config.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <newsletter>
            <referral>
                <invite_friend_email_template>
                    newsletter_referral_invite_friend_email_template
                </invite_friend_email_template>
            </referral>
        </newsletter>
    </default>
</config>

etc/email_templates.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="newsletter_referral_invite_friend_email_template"
              label="Invite Friend Email"
              file="invite_friend.html"
              type="html"
              module="Ped_Referral"
              area="frontend"/>
</config>

view/frontend/email/invite_friend.html

<!--@subject {{trans "You have been invited to register"}} @-->

{{template config_path="design/email/header_template"}}

<p>
    {{trans "You have been invited to register" }}
</p>

{{template config_path="design/email/footer_template"}}

Controller action to send email

<?php
declare(strict_types=1);

namespace Ped\Referral\Controller\Customer;

use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Area;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\MailException;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Newsletter\Model\Queue\TransportBuilder;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\Store;
use Magento\Store\Model\StoreManagerInterface;
use Ped\Referral\Controller\Customer;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Exception\NoSuchEntityException;

class Invite extends Customer
{
    private const XML_PATH_EMAIL_INVITE_FRIEND = 'newsletter/referral/invite_friend_email_template';

    /**
     * @var Validator
     */
    private $formKeyValidator;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var TransportBuilder
     */
    private $transportBuilder;

    /**
     * @var ScopeConfigInterface
     */
    private $scopeConfig;

    /**
     * @var StateInterface
     */
    private $inlineTranslation;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * Invite constructor.
     * @param Context $context
     * @param Session $customerSession
     * @param Validator $formKeyValidator
     * @param LoggerInterface $logger
     * @param TransportBuilder $transportBuilder
     * @param ScopeConfigInterface $scopeConfig
     * @param StateInterface $inlineTranslation
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        Context $context,
        Session $customerSession,
        Validator $formKeyValidator,
        LoggerInterface $logger,
        TransportBuilder $transportBuilder,
        ScopeConfigInterface $scopeConfig,
        StateInterface $inlineTranslation,
        StoreManagerInterface $storeManager
    ) {
        parent::__construct($context, $customerSession);
        $this->formKeyValidator = $formKeyValidator;
        $this->logger = $logger;
        $this->transportBuilder = $transportBuilder;
        $this->scopeConfig = $scopeConfig;
        $this->inlineTranslation = $inlineTranslation;
        $this->storeManager = $storeManager;
    }

    /**
     * Validate form key
     * @return bool
     */
    private function validateFormKey(): bool
    {
        return $this->formKeyValidator->validate($this->getRequest());
    }

    /**
     * Validate request params
     * @return bool
     * @throws LocalizedException
     */
    private function validateParams(): bool
    {
        $email = $this->getRequest()->getParam('email');

        if (strpos($email, '@') === false) {
            throw new LocalizedException(__('The email address is invalid. Verify the email address and try again.'));
        }

        return true;
    }

    /**
     * Send referral email message
     * @param $email
     * @throws MailException
     * @throws NoSuchEntityException
     */
    private function sendMessage($email): void
    {
        $storeId = $this->storeManager->getStore((int)$this->getCustomer()->getStoreId())->getId();
        $templateId = $this->scopeConfig->getValue(
            self::XML_PATH_EMAIL_INVITE_FRIEND,
            ScopeInterface::SCOPE_STORE,
            $storeId
        );

        $transport = $this->transportBuilder
            ->setTemplateIdentifier($templateId)
            ->setTemplateOptions([
                'area' => Area::AREA_FRONTEND,
                'store' => $storeId,
            ])
            ->setTemplateVars([
                'name' => $this->getCustomer()->getName(),
            ])
            ->setFrom([
                'name' => $this->getCustomer()->getName(),
                'email' => $this->getCustomer()->getEmail(),
            ])
            ->addTo($email)
            ->getTransport();

        $transport->sendMessage();
    }

    /**
     * Send referral email message to customer's friend
     * @return ResponseInterface|Redirect|ResultInterface
     */
    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();

        if (!$this->validateFormKey()) {
            return $resultRedirect->setRefererUrl();
        }

        $email = $this->getRequest()->getParam('email');

        try {
            $this->validateParams();

            $this->inlineTranslation->suspend();
            $this->sendMessage($email);
            $this->inlineTranslation->resume();

            $this->logger->info('Sent referral email message to ' . $email);
            $this->messageManager->addSuccessMessage(__('Email sent successfully'));
        } catch (LocalizedException $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
        } catch (\Exception $e) {
            $this->logger->critical($e);
            $this->messageManager->addErrorMessage(
                __('An error occurred while processing your form. Please try again later.')
            );
        }

        return $resultRedirect->setPath('referral/customer/index');
    }
}

Why do I receive a blank email? (without subject neither body)

0

The error was that I used:

use Magento\Newsletter\Model\Queue\TransportBuilder;

instead of:

use Magento\Framework\Mail\Template\TransportBuilder;

  • can you explain your answer how did you fix the issue? – user3766719 Aug 3 at 7:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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