2

Magento 2 - How can I send new mail to customer, if any order has been placed by banktransfer and more that 7 days since order placed.

I need to send mail using Crons.

This is my code:

<?php

namespace Arnavcancleorder\Cancleorder\Cron;

use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\Search\FilterGroup;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Sales\Api\OrderManagementInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\Framework\App\RequestInterface;


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

    private $orderRepository;

    /**
     * @var SearchCriteriaBuilder
     */
    private $searchCriteriaBuilder;

    private $filterBuilder;
    private $filterGroup;
    private $orderManagement;

    protected $_request;
    protected $_transportBuilder;
    protected $_storeManager;


    public function __construct(
        OrderRepositoryInterface $orderRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        FilterBuilder $filterBuilder,
        FilterGroup $filterGroup,
        OrderManagementInterface $orderManagement,
        \Magento\Framework\App\Action\Context $context
        , \Magento\Framework\App\Request\Http $request
        , \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder
        , \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {
        $this->orderRepository       = $orderRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->filterBuilder         = $filterBuilder;
        $this->filterGroup           = $filterGroup;
        $this->orderManagement       = $orderManagement;
        $this->_request = $request;
        $this->_transportBuilder = $transportBuilder;
        $this->_storeManager = $storeManager;
        parent::__construct($context);
    }


    public function execute()
    {
        $today          = date("Y-m-d h:i:s");
        $to             = strtotime('-2 min', strtotime($today));
        $to             = date('Y-m-d h:i:s', $to);

        $filterGroupDate      = $this->filterGroup;
        $filterGroupStatus    = clone($filterGroupDate);
        $filterGroupEmail      = clone($this->filterGroup);


        $filterDate      = $this->filterBuilder
            ->setField('updated_at')
            ->setConditionType('to')
            ->setValue($to)
            ->create();
        $filterStatus    = $this->filterBuilder
            ->setField('status')
            ->setConditionType('eq')
            ->setValue('ced_credit_limit')
            ->create();

            $filterEmail  = $this->filterBuilder
                    ->setField('email_msg')
                    ->setConditionType('eq')
                    ->setValue('2')
                    ->create();

            $filterGroupDate->setFilters([$filterDate]);
            $filterGroupStatus->setFilters([$filterStatus]);
            $filterGroupEmail->setFilters([$filterEmail]);


            $searchCriteria = $this->searchCriteriaBuilder->setFilterGroups(
                [$filterGroupDate, $filterGroupStatus,$filterGroupEmail]


        );
        $searchResults  = $this->orderRepository->getList($searchCriteria->create());



        foreach ($searchResults->getItems() as $order) {
           $names=$order->getCustomerEmail();

          $store = $this->_storeManager->getStore()->getId();
        $transport = $this->_transportBuilder->setTemplateIdentifier('40')
            ->setTemplateOptions(['area' => 'frontend', 'store' => $store])
            ->setTemplateVars(
                [
                    'store' => $this->_storeManager->getStore(),
                ]
            )
            ->setFrom('general')
            // you can config general email address in Store -> Configuration -> General -> Store Email Addresses
            ->addTo($names)
            ->getTransport();
        $transport->sendMessage();
        return $this;
        }
    }
}
1
  • What email you want to send? Magento order email or any other custom email? Commented Sep 7, 2018 at 13:47

1 Answer 1

2

Create a module with name STech_Order and create the files like below steps:

Step 1: Create registration.php under:

app/code/STech/Order/registration.php

with below content:

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'STech_Order',
    __DIR__
);

Step 2: Create module.xml under:

app/code/STech/Order/etc/module.xml

with below content:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="STech_Order" setup_version="0.0.1">
        <sequence>
            <module name="Magento_Backend"/>
            <module name="Magento_Sales"/>
        </sequence>
    </module>
</config>

Step 3: Create crontab.xml under:

app/code/STech/Order/etc/crontab.xml

with below content:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job name="order_mail" instance="STech\Order\Cron\Run" method="execute">
            <schedule>*/1 * * * *</schedule>
        </job>
    </group>
</config>

Step 4: Create Run.php under:

app/code/STech/Order/Cron/Run.php

with below content:

<?php
namespace STech\Order\Cron;

class Run 
{
    protected $_logger;
    protected $_orderCollectionFactory;

    public function __construct(
        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory
    ){
        $this->_orderCollectionFactory = $orderCollectionFactory;
    }

    public function execute()
    {
        foreach($this->getOrders() as $order){
            echo $order->getIncrementId();
            // Do your email code
        }
        return $this;
    }

    public function getOrders()
    {
        $pMethod = 'banktransfer';
        $to = date("Y-m-d h:i:s");
        $from = strtotime('-7 day', strtotime($to));
        $from = date('Y-m-d h:i:s', $from);

        $collection = $this->_orderCollectionFactory->create()->addAttributeToSelect('*');
        $collection->addFieldToFilter('created_at', array('from'=>$from, 'to'=>$to));
        $collection->getSelect()->join(["sop" => "sales_order_payment"], 'main_table.entity_id = sop.parent_id', array('method'))->where('sop.method = ?',$pMethod);
        return $collection;
    }
}

Change cron settings according to your requirement.

Run setup upgrade, di compile and other required commands and test.

7
  • Thanks a lot for comment MR.Sukumar Gorai , i have one small doubt ,actually i want to send an email (from email template) to customers based on who all are crossed 7 days from order placed time & date . Commented Sep 8, 2018 at 5:04
  • you can try this webkul.com/blog/magento2-create-custom-email-templates Commented Sep 8, 2018 at 5:47
  • If you dont mine please check my code once , in this iam checking 3 condition if it satifies email shoud go once only , but here its going to only one customer and may times Commented Sep 8, 2018 at 6:02
  • You need to create one table for your custom module and add the order ids when email is sent for flag so that email will not send next. You need to check the flag before sending email. Commented Sep 8, 2018 at 6:14
  • ok, what i did is i created extra column in sales order , after email has sent to customer ia trying to instert some value in that column using object manager direct update query in side execute() funtion but it not inserting , any idea please i was trying a lot for this please help me on this thanks Commented Sep 8, 2018 at 6:23

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.