0

I have stuck in sending mail to store owner in the below code, but I don't how to programmatically send email to store owner.

Please check my below code and help me solve out.

<?php
/**
 * KiwiCommerce
 *
 * Do not edit or add to this file if you wish to upgrade to newer versions in the future.
 * If you wish to customize this module for your needs.
 * Please contact us https://kiwicommerce.co.uk/contacts.
 *
 * @category   KiwiCommerce
 * @package    KiwiCommerce_AdminActivity
 * @copyright  Copyright (C) 2018 Kiwi Commerce Ltd (https://kiwicommerce.co.uk/)
 * @license    https://kiwicommerce.co.uk/magento2-extension-license/
 */
namespace KiwiCommerce\AdminActivity\Cron;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Filesystem\DirectoryList;
use Psr\Log\LoggerInterface;
use KiwiCommerce\AdminActivity\Helper\Data as Helper;
use KiwiCommerce\AdminActivity\Api\ActivityRepositoryInterface;

/**
 * Class ClearLog
 * @package KiwiCommerce\AdminActivity\Cron
 */
class ClearLog extends \Magento\Framework\App\Action\Action
{
    /**
     * Default date format
     * @var string
     */
    const DATE_FORMAT = 'Y-m-d H:i:s';
    /**
     * @var LoggerInterface
     */
    protected $fileFactory;
    protected $csvProcessor;
    protected $directoryList;

    public $logger;
    /**
     * @var \Magento\Framework\Stdlib\DateTime\DateTime
     */
    public $dateTime;
    /**
     * @var \KiwiCommerce\AdminActivity\Helper\Data
     */
    public $helper;
    /**
     * @var ActivityRepositoryInterface
     */
    public $activityRepository;
    /**
     * @var \KiwiCommerce\AdminActivity\Api\LoginRepositoryInterface
     */
    public $loginRepository;

    /**
     * ClearLog constructor.
     * @param LoggerInterface $logger
     * @param \Magento\Framework\Stdlib\DateTime\DateTime $dateTime
     * @param Helper $helper
     * @param ActivityRepositoryInterface $activityRepository
     * @param \KiwiCommerce\AdminActivity\Api\LoginRepositoryInterface $loginRepository
     */
    public function __construct(
        LoggerInterface $logger,
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Framework\Stdlib\DateTime\DateTime $dateTime,
        Helper $helper,
        ActivityRepositoryInterface $activityRepository,
        \KiwiCommerce\AdminActivity\Api\LoginRepositoryInterface $loginRepository
    ) {
        $this->logger = $logger;
        $this->dateTime = $dateTime;
        $this->helper = $helper;
        $this->activityRepository = $activityRepository;
        $this->loginRepository = $loginRepository;
        $this->_fileFactory = $fileFactory;
        $this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
        parent::__construct($context);
    }
    /**
     * Return cron cleanup date
     * @return null|string
     */
    public function __getDate()
    {
        $timestamp = $this->dateTime->gmtTimestamp();
        $day = $this->helper->getConfigValue('CLEAR_LOG_DAYS');
        if ($day) {
            $timestamp -= $day * 24 * 60 * 60;
            return $this->dateTime->gmtDate(self::DATE_FORMAT, $timestamp);
        }
        return null;
    }
    /**
     * Delete record which date is less than the current date
     * @return $this|null
     */
    public function execute()
    {
        try {
            if (!$this->helper->isEnable()) {
                return $this;
            }

            if ($date = $this->__getDate()) {

                $activities = $this->activityRepository->getListBeforeDate($date);

                $name = date('m_d_Y_H_i_s');

                $filepath = 'export/Adminactivity/admin_activity_' . $name . '.csv';
                $loginfilepath = 'export/Loginactivity/login_activity_' . $name . '.csv';

                $this->directory->create('export');
                  /* Open file */
                $stream = $this->directory->openFile($filepath, 'w+');

                $stream->lock();

                $columns = $this->getColumnHeader();

                foreach ($columns as $column) {
                    $header[] = $column;
                }

                /* Write Header */
                $stream->writeCsv($header);

                if (!empty($activities)) {
                    foreach ($activities as $activity) {
                        $activityArray = [];
                        $activityArray[] = $activity['entity_id'];
                        $activityArray[] = $activity['username'];
                        $activityArray[] = $activity['name'];
                        $activityArray[] = $activity['admin_id'];
                        $activityArray[] = $activity['store_id'];
                        $activityArray[] = $activity['scope'];
                        $activityArray[] = $activity['action_type'];
                        $activityArray[] = $activity['remote_ip'];
                        $activityArray[] = $activity['forwarded_ip'];
                        $activityArray[] = $activity['user_agent'];
                        $activityArray[] = $activity['module'];
                        $activityArray[] = $activity['fullaction'];
                        $activityArray[] = $activity['item_name'];
                        $activityArray[] = $activity['item_url'];
                        $activityArray[] = $activity['is_revertable'];
                        $activityArray[] = $activity['revert_by'];
                        $activityArray[] = $activity['created_at'];
                        $activityArray[] = $activity['updated_at'];
                        $stream->writeCsv($activityArray);
                        $activity->delete($activity['entity_id']);
                    }
                }


                //TODO: Remove login activity detail
                if ($this->helper->isLoginEnable()) {

                    $streamLogin = $this->directory->openFile($loginfilepath, 'w+');
                    $streamLogin->lock();
                    $loginColumns = $this->getLoginColumnHeader();

                    foreach ($loginColumns as $columnLog) {
                        $headerLogin[] = $columnLog;
                    }

                    $streamLogin->writeCsv($headerLogin);

                    $loginactivities = $this->loginRepository->getListBeforeDate($date);
                    if (!empty($loginactivities)) {
                        foreach ($loginactivities as $activity) {
                            $loginArray = [];
                            $loginArray[] = $activity['entity_id'];
                            $loginArray[] = $activity['username'];
                            $loginArray[] = $activity['name'];
                            $loginArray[] = $activity['remote_ip'];
                            $loginArray[] = $activity['forwarded_ip'];
                            $loginArray[] = $activity['user_agent'];
                            $loginArray[] = $activity['type'];
                            $loginArray[] = $activity['status'];
                            $loginArray[] = $activity['remarks'];
                            $loginArray[] = $activity['created_at'];

                            $streamLogin->writeCsv($loginArray);
                            $activity->delete($activity['entity_id']);
                        }
                    }
                }
            }
        } 
        catch (\Exception $e) {
           $this->logger->debug($e->getMessage());
        }
        return null;
    }

    /* Header Columns */
    public function getColumnHeader() {
        $headers = ['entity_id','username','name','admin_id','store_id','scope','action_type','remote_ip','forwarded_ip','user_agent','module','fullaction','item_name','item_url','is_revertable','revert_by','created_at','updated_at'];
        return $headers;
    }

    /* Header Columns */
    public function getLoginColumnHeader() {
        $headers = ['entity_id','username','name','remote_ip','forwarded_ip','user_agent','type','status','remarks','created_at'];
        return $headers;
    }

}

Thanks For Advanced...

0

You can try the process describe below.

step 1)

Create a email_templates.xml under app/code/KiwiCommerce/AdminActivity/etc

File: YOUR-MAGENTO-ROOT/app/code/KiwiCommerce/AdminActivity/etc/email_templates.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../Email/etc/email_templates.xsd">
    <template id="custom_admin_email_template" label="Custom Admin Email" file="custom_adminmail.html" type="html" module="Matrixmedia_CustomeImportmail" area="frontend"/>
</config>

step 2)

Create HTML email template file custom_adminmail.html under app/code/KiwiCommerce/AdminActivity/view/frontend/email/

File: YOUR-MAGENTO-ROOT/app/code/KiwiCommerce/AdminActivity/view/frontend/email/custom_adminmail.html

<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<!--@subject {{trans "Welcome to %store_name" store_name=$store.getFrontendName()}} @-->


{{template config_path="design/email/header_template"}}
<p>{{trans "welcome you to %store_name. " store_name=$store.getFrontendName()}}</p>

<ul>
    <li><strong>{{trans "Info 1:"}}</strong> {{var var_1}}</li>
    <li><strong>{{trans "Info 2:"}}</strong> {{var var_2}}</li>
    <li><strong>{{trans "Info 3:"}}</strong> {{var var_3}}</li>
    <li><strong>{{trans "Info 4:"}}</strong> {{var var_4}}</li>
</ul>


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

step 3)

Update your cron file as below

File: YOUR-MAGENTO-ROOT/app/code/KiwiCommerce/Cron/ClearLog.php

<?php

......................
......................
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Mail\Template\TransportBuilder;
......................
......................
......................




 class ClearLog extends \Magento\Framework\App\Action\Action
{

 ......................     
 const XML_PATH_CUSTOM_ADMIN_EMAIL_TEMPLATE = 'custom_admin_email_template';
 ......................

 public function __construct(         
         ...................... ,
         ...................... ,
         TransportBuilder $transportBuilder,
         \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
         ScopeConfigInterface $scopeConfig,
         StoreManagerInterface $storeManager,         
         ...................... ,
         ...................... ,

    ) {

        ...................... ,
        ...................... ,
        $this->storeManager = $storeManager;
        $this->scopeConfig = $scopeConfig;
        $this->transportBuilder = $transportBuilder;
        $this->inlineTranslation = $inlineTranslation;
        ...................... ,
        ...................... ,

    }


    public function execute()
    {

        ......................
        ...................... ,


        try{
             $storeid = 1;
             $store = $this->storeManager->getStore($storeid); // Chnage Store ID
             $AdminEmailId =  'admin@abc.com'; // Change Admin Email
             $templateId = self::XML_PATH_CUSTOM_ADMIN_EMAIL_TEMPLATE,
             //Set Email Template var
             $templateParams = [
              'store' => $store, 
              'var_1'=>'TEST 1',
              'var_2'=>'TEST 2',
              'var_3'=>'TEST 3',
              'var_3'=>'TEST 4'
             ];
             $isEmailSendSuccess = $this->sendEmailToAdmin(
             $AdminEmailId,
             self::XML_PATH_CUSTOM_IMPORT_EMAIL_TEMPLATE,                                         
             $templateParams
            );

            } catch (\Exception $e) {
              $message = $e->getMessage();                
              $this->logger->info("Error:".$message);       

         }          





    }

private function sendEmailToAdmin($AdminEmail, $templateId,$templateParams = []){                                    
         try{ 
              $this->inlineTranslation->suspend();
              $error = false;
              $sender = [
                 'name' =>  $this->scopeConfig->getValue('trans_email/ident_general/name',\Magento\Store\Model\ScopeInterface::SCOPE_STORE),
                 'email' => $this->scopeConfig->getValue('trans_email/ident_general/email',\Magento\Store\Model\ScopeInterface::SCOPE_STORE)
                 ];
               $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
               $transport = $this->transportBuilder
               ->setTemplateIdentifier($templateId) // this code we have mentioned in the email_templates.xml
                ->setTemplateOptions(
                 [
                   'area' => \Magento\Framework\App\Area::AREA_FRONTEND, // this is using frontend area to get the template file
                   'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
                  ]
                 )
                 ->setTemplateVars($templateParams)
                 ->setFrom($sender)
                 ->addTo($AdminEmail)                
                 ->getTransport();
                 $transport->sendMessage();
                 $this->inlineTranslation->resume();            
                 return true;             
          } catch (\Exception $e) {
              $message = $e->getMessage();
              $this->logger->info("==== Admin Custom  Email Send error=".$message);
              return false;           
          }                     

    }

?>

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.