0

I want to create a customer account in Magento 2.4 from cron. And I want to send a welcome email with a reset password link.

I have found a few articles that helped me to create a customer account. But didn't find any solution for sending a welcome email with a reset password link on a newly created customer account.

Thanks in advance

2 Answers 2

0

You can try below code for sending reset password emails.

public function __construct(
    Magento\Framework\App\Action\Context $context,
    Magento\Customer\Model\Session $customerSession,
    Magento\Customer\Api\AccountManagementInterface $customerAccountManagement,
) {
    $this->session = $customerSession;
    $this->customerAccountManagement = $customerAccountManagement;
    parent::__construct($context);
}


public function sendCustomMail()
{

            $email = 'YOURCUSTOMEREMAILADDRESS'; 

            if (!\Zend_Validate::is($email, 'EmailAddress')) {
                $this->session->setForgottenEmail($email);
                $this->messageManager->addErrorMessage(__('Please correct the email address.'));
            }

            try {
                $this->customerAccountManagement->initiatePasswordReset(
                    $email,
                    AccountManagement::EMAIL_RESET
                );
            } catch (NoSuchEntityException $e) {
                // Do nothing, we don't want anyone to use this action to determine which email accounts are registered.
            } catch (\Exception $exception) {
                $this->messageManager->addExceptionMessage(
                    $exception,
                    __('We\'re unable to send the password reset email.')
                );
            }
            $this->messageManager->addSuccessMessage($this->getSuccessMessage($email));
}
0

app/code/VendoreName/ModuleName/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 area="frontend" file="customersendemail.html" id="custom_reset_password" label="Customer Reset Password Custom" module="VendoreName_ModuleName" type="html"/>
</config>

app/code/VendoreName/ModuleName/view/frontend/email

customersendemail.html

<!--@subject {{trans "Account Created - Reset Your Password"}}  @-->
{{template config_path="design/email/header_template"}}

<p class="greeting">{{trans "%name," name=$customer.name}}</p>
<p>{{trans "Welcome to"}}{{trans "%store_name" store_name=$store.frontend_name}}.</p>

<table class="button" width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td>
            <table class="inner-wrapper" border="0" cellspacing="0" cellpadding="0" align="center">
                <tr>
                    <td align="center">
                        <a href="{{var this.getUrl($store,'customer/account/createPassword/',[_query:[token:$customer.rp_token],_nosid:1])}}" target="_blank">{{trans "Set a New Password"}}</a>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
</table>

<p>{{trans 'Thank you for your registration. '}}</p>

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

app/code/VendoreName/ModuleName/Cron

CronClassName.php

<?php

namespace VendoreName\ModuleName\Cron;

use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Filesystem\DirectoryList;
use Magento\Framework\Mail\Template\SenderResolverInterface;
use Magento\Framework\Reflection\DataObjectProcessor;

class CronClassName
{
    protected $resultPageFactory;
    protected $customer;
    protected $storeManager;
    protected $scopeConfig;
    protected $transportBuilder;
    protected $customerRegistry;
    protected $dataProcessor;
    protected $_customerRepository;
    protected $_mathRandom;
    protected $_accountmanagement;

    public function __construct(
        .................................................................
        \Magento\Customer\Model\CustomerFactory $customer,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        \Magento\Framework\Mail\Template\SenderResolverInterface $senderResolver,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        \Magento\Framework\Math\Random $mathRandom,
        \Magento\Customer\Model\AccountManagement $accountmanagement,
        \Magento\Framework\Reflection\DataObjectProcessor $dataProcessor,
        \Magento\Customer\Model\CustomerRegistry $customerRegistry,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        .................................................................
    ) {
        .................................................................
        $this->resultPageFactory = $resultPageFactory;
        $this->storeManager = $storeManager;
        $this->customer = $customer;
        $this->transportBuilder = $transportBuilder;
        $this->scopeConfig = $scopeConfig;
        $this->dataProcessor = $dataProcessor;
        $this->_accountmanagement = $accountmanagement;
        $this->_customerRepository = $customerRepository;
        $this->_mathRandom = $mathRandom;
        $this->customerRegistry = $customerRegistry;
        $this->senderResolver = $senderResolver ?? ObjectManager::getInstance()->get(SenderResolverInterface::class);
        .................................................................
    }

    public function createCustomer($data, $websiteId, $emailTemplate)
    {
        $data =  "array of customer Data";
        $emailTemplate = "custom_reset_password";

        if (isset($data['id'])) {
            $checkCustomer = $this->customer->create()->setWebsiteId($websiteId)->loadByEmail($data['id']);
        } else{
            $checkCustomer = $this->customer->create();
        }
        if (!$checkCustomer->hasData()) {
            try {
                $createCustomer = $this->customer->create();
                $createCustomer->setWebsiteId($websiteId);
                $createCustomer->setEmail($data['email']);
                $createCustomer->setFirstname($data['f_name']);
                $createCustomer->setLastname($data['l_name']);
                $createCustomer->setGroupId($data['group_id']);
                $createCustomer->save();

                /* Send Email TO Customer */
                $emailSendStatus = $this->sendEmailToCustomer($createCustomer, $emailTemplate);

            } catch (Exception $e) {
                $msg = 'Something went wrong when creating customer.';
            }
        } else {
            $msg = 'Customer Already Created.';
        }
    }

    public function getStoreId($websiteId)
    {
        return $this->storeManager->getWebsite($websiteId)->getDefaultStore()->getId();
    }

    public function sendEmailToCustomer($customer, $emailTemplate)
    {
        $storeId = $this->getStoreId($customer->getWebsiteId());
        $customerEmailData = $this->getFullCustomerObject($customer);
        $templateParams = [];
        $templateParams['customer'] = $customerEmailData;
        $templateParams['store'] = $this->storeManager->getStore($storeId);

        $sender = \Magento\Customer\Model\EmailNotification::XML_PATH_FORGOT_EMAIL_IDENTITY;

        $from = $this->senderResolver->resolve(
            $this->scopeConfig->getValue($sender, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId),
            $storeId
        );

        $customerName = $customer->getFirstname() . " " . $customer->getLastname();

        try {
            $transport = $this->transportBuilder->setTemplateIdentifier($emailTemplate)
                ->setTemplateOptions(['area' => 'frontend', 'store' => $storeId])
                ->setTemplateVars($templateParams)
                ->setFrom($from)
                ->addTo($customer->getEmail(), $customerName)
                ->getTransport();
            $transport->sendMessage();
            $this->logger->info($customer->getEmail() . ' : Email Send Successfully.');
        } catch (Exception $e) {
            $this->logger->error($customer->getEmail() . ' : Something went wrong when sending email');
        }
    }

    public function getFullCustomerObject($customer)
    {
        $mergedCustomerData = $this->customerRegistry->retrieveSecureData($customer->getId());
        $customerData = $this->dataProcessor
            ->buildOutputDataArray($customer, CustomerInterface::class);
        $mergedCustomerData->addData($customerData);
        $customerName = $customer->getFirstname() . " " . $customer->getLastname();
        $mergedCustomerData->setData('name', $customerName);
        $tokenVal = $this->getToken($customer->getEmail(), $customer->getWebsiteId());
        $mergedCustomerData->setData('rp_token', $tokenVal);
        return $mergedCustomerData;
    }

    public function getToken($email, $websiteId)
    {
        $customer = $this->_customerRepository->get($email, $websiteId);
        $newPasswordToken = $this->_mathRandom->getUniqueHash();
        $this->_accountmanagement->changeResetPasswordLinkToken($customer, $newPasswordToken);
        return $newPasswordToken;
    }
}

Here you need to call createCustomer($data, $websiteId, $emailTemplate) function where $data has customer data, $websiteId is website id and $emailTemplate is our custom email template name.

Your Answer

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

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