PHP mail function how to set recipient mail id based on if condition?

I am using magento for sending mail with condition,

My code:

<?php
class Gta_MerchantNotification_Model_Observer {
    public function merchantremainder($Observer) {
       $order = $Observer->getEvent()->getOrder();
       $order_details = $order->getAllVisibleItems();

       $itemData = array();
       foreach ($order_details as $list) {
          $incrementid = $order->getIncrementId();
          $sku = $list->getsku();
          $name = $list->getName();
          $price = $list->getPrice();
          $Qty = $list->getQtyOrdered();
          $extra = $order->getIncrementId();
          $message = 

          "
          <tr>
          <!-- <td>$incrementid</td> -->
          <td>$sku</td>
          <td>$name</td>
          <td>$price</td>
          <td>$Qty</td>
          </tr>";

          $itemData[$list->getId()] = $message;

      }
  
      $finalMessage =  "
      <p>Order Id : $incrementid</p>
      <table border='1'>

      <tr>
      <!-- <th>Id</th> -->
      <th>Sku</th>
      <th>Product name</th>
      <th>Price</th>
      <th>Qty Ordered</th>
      </tr>";
      if (!empty($itemData)) {
          foreach ($itemData as $data) {
             $finalMessage .= $data;
         }

         $finalMessage .= "</table>";
         $this->sendMail($finalMessage);
     }

 }

 public function sendMail($message) {
   $body ="$message";
   $emailTemplate = Mage::getModel('core/email');
   $emailTemplate->setFromName('abc');
   $emailTemplate->setBody($body);
   $emailTemplate->setSubject("Custom Email from observer");
   $emailTemplate->setType('html');
   $emailTemplate->setToEmail('abc@gmail.com');
   $emailTemplate->send();

}
}

?>

Output :

If order placed mail send to abc@gmail.com.
How to set recipient email based on SKU $sku from order.

I want :

  1. If SKU starts with 2, email should go to the mail id abc@gmail.com,
    screenshot :

  1. If SKU starts with 3, email should go to the mail id xyz@gmail.com,
    screenshot :

  1. If SKU starts with 4, email should go to the mail id qwe@gmail.com,
    screenshot :

FYI - If an order contains 10 items email should go separately based on SKU. But an order id the same must include all the emails.

Can you clarify, do you want to set the “sender” (i.e. the address you send the email from )

or

do you want to set the “recipient”, i.e the address you send the email to.

In any case, I would loop through the order information and build an order email for each address, based on whatever rules you want. Once done, I would then send each email to/from the appropriate place.

Probably change $itemData to be a two-dimensional array, where the first dimension is the first digit of the sku, or whatever other rule you have to split the orders. Your first loop builds up the array exactly as it does now but splitting by that digit, then you’d have a loop around $finalMessage for each part of $itemData[sku-first-digit] that has any entries in it.

Can you describe more about why you want to send the email differently depending on the first digit of the SKU? It sounds like quite a dangerous thing to do.

recipient email

OK, as above. When you loop through each item, add it to

$itemData[$digit][$list->getId()] = $message;

then loop through $itemData to build the messages. Obviously $digit is the first digit of the SKU, or whatever other way you want to group them.

Here what is the role $digit, how to write the function like take first digit of $sku?

By making it into the first element of the array, you can foreach() over the finished array, check for the index changing, and use that to easily build each email message.

Well, you could use substr(), or take advantage of the fact that PHP strings are arrays and just access the first element of the array.

1 Like

Any help with my error,

Code :

<?php
class Gta_MerchantNotification_Model_Observer {
  public function merchantremainder($Observer) {
    $order = $Observer->getEvent()->getOrder();
    $order_details = $order->getAllVisibleItems();

    $itemData = array();
    foreach ($order_details as $list) {
      $incrementid = $order->getIncrementId();
      $sku = $list->getsku();
      $name = $list->getName();
      $price = $list->getPrice();
      $Qty = $list->getQtyOrdered();

      $this->sendMailbasedOnSku($sku);

      $message = "<tr>
      <!-- <td>$incrementid</td> -->
      <td>$sku</td>
      <td>$name</td>
      <td>$price</td>
      <td>$Qty</td>
      </tr>";

      $itemData[$list->getId()] = $message;

    }

    $finalMessage = "
    <p>Order Id : $incrementid</p>
    <table border='1'>
    <tr>
    <!-- <th>Id</th> -->
    <th>Sku</th>
    <th>Product name</th>
    <th>Price</th>
    <th>Qty Ordered</th>
    </tr>";

    if (!empty($itemData)) {
      foreach ($itemData as $data) {
        $finalMessage .= $data;
      }

      $finalMessage .= "</table>";

      $this->sendMail($finalMessage);

    }

  }

  public function sendMail($message) {

    $body = "$message";
    $emailTemplate = Mage::getModel('core/email');
    $emailTemplate->setFromName('Test mail');
    $emailTemplate->setBody($body);
    $emailTemplate->setSubject("Custom Email from observer");
    $emailTemplate->setType('html');
// $emailTemplate->setToEmail('abc@gmail.com');

    if($sku == '2')
    {
      $emailTemplate->setToEmail('abc@gmail.com');
    }

    elseif($sku == '3')
    {
      $emailTemplate->setToEmail('xyz@gmail.com');    
    }

    elseif($sku == '4')
    {
      $emailTemplate->setToEmail('qwe@gmail.com');    
    }

    else
    {
      $emailTemplate->setToEmail('ewq@gmail.com');
    }



    $emailTemplate->send();


  }

  public function sendMailbasedOnSku($sku)
  {

// sku is 22302

    $chk_sku=(int)substr($sku, 0, 1);

    if($chk_sku == '2')
    {
      $emailTemplate->setToEmail('abc@gmail.com');
    }

    elseif($chk_sku == '3')
    {
      $emailTemplate->setToEmail('xyz@gmail.com');    
    }

    elseif($chk_sku == '4')
    {
      $emailTemplate->setToEmail('qwe@gmail.com');    
    }

    else{
      $emailTemplate->setToEmail('ewq@gmail.com');
    }

    try{
    return $emailTemplate->send();
    Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
  }

  catch (Exception $e) {
    Mage::getSingleton('core/session')->addError($e->getMessage());
  }

  }



}

?>

error :

[09-Jan-2020 04:53:42 UTC] PHP Fatal error:  Uncaught Error: Call to a member function setToEmail() on null in C:\wamp64\www\magento\app\code\local\Gta\MerchantNotification\Model\Observer.php:99
Stack trace:
#0 C:\wamp64\www\magento\app\code\local\Gta\MerchantNotification\Model\Observer.php(15): Gta_MerchantNotification_Model_Observer->sendMailbasedOnSku('22')
#1 C:\wamp64\www\magento\app\code\core\Mage\Core\Model\App.php(1358): Gta_MerchantNotification_Model_Observer->merchantremainder(Object(Varien_Event_Observer))
#2 C:\wamp64\www\magento\app\code\core\Mage\Core\Model\App.php(1337): Mage_Core_Model_App->_callObserverMethod(Object(Gta_MerchantNotification_Model_Observer), 'merchantremaind...', Object(Varien_Event_Observer))
#3 C:\wamp64\www\magento\app\Mage.php(448): Mage_Core_Model_App->dispatchEvent('checkout_submit...', Array)
#4 C:\wamp64\www\magento\app\code\core\Mage\Checkout\Model\Type\Onepage.php(872): Mage::dispatchEvent('checkout_submit...', Array)
#5 C:\wamp64\www\magento\app\code\core\Mage\Checkout\controllers\OnepageController.php(579): M in C:\wamp64\www\magento\app\code\local\Gta\MerchantNotification\Model\Observer.php on line 99

In your sendMailbasedonsku() function, where does $emailTemplate get defined? I see how you create it in sendMail(), but not in the other function.

I also didn’t intend that you’d send the emails from within the first foreach() loop - doing it that way, if you have ten items and each one is to be emailed to the same place, they’ll all go as individual email messages.

After declare $emailTemplate = Mage::getModel(‘core/email’);

Code :

<?php
class Gta_MerchantNotification_Model_Observer {
  public function merchantremainder($Observer) {
    $order = $Observer->getEvent()->getOrder();
    $order_details = $order->getAllVisibleItems();

    $itemData = array();
    foreach ($order_details as $list) {
      $incrementid = $order->getIncrementId();
      $sku = $list->getsku();
      $name = $list->getName();
      $price = $list->getPrice();
      $Qty = $list->getQtyOrdered();

      $this->sendMailbasedOnSku($sku);

      $message = "<tr>
      <!-- <td>$incrementid</td> -->
      <td>$sku</td>
      <td>$name</td>
      <td>$price</td>
      <td>$Qty</td>
      </tr>";

      $itemData[$list->getId()] = $message;

    }

    $finalMessage = "
    <p>Order Id : $incrementid</p>
    <table border='1'>
    <tr>
    <!-- <th>Id</th> -->
    <th>Sku</th>
    <th>Product name</th>
    <th>Price</th>
    <th>Qty Ordered</th>
    </tr>";

    if (!empty($itemData)) {
      foreach ($itemData as $data) {
        $finalMessage .= $data;
      }

      $finalMessage .= "</table>";

      $this->sendMail($finalMessage);

    }

  }

  public function sendMail($message) {

    $body = "$message";
    $emailTemplate = Mage::getModel('core/email');
    $emailTemplate->setFromName('Test mail');
    $emailTemplate->setBody($body);
    $emailTemplate->setSubject("Custom Email from observer");
    $emailTemplate->setType('html');
// $emailTemplate->setToEmail('abc@gmail.com');

    if($sku == '2')
    {
      $emailTemplate->setToEmail('abc@gmail.com');
    }

    elseif($sku == '3')
    {
      $emailTemplate->setToEmail('xyz@gmail.com');    
    }

    elseif($sku == '4')
    {
      $emailTemplate->setToEmail('qwe@gmail.com');    
    }

    else
    {
      $emailTemplate->setToEmail('ewq@gmail.com');
    }



    $emailTemplate->send();


  }

  public function sendMailbasedOnSku($sku)
  {

    $emailTemplate = Mage::getModel('core/email');

    $chk_sku=(int)substr($sku, 0, 1);

    if($chk_sku == '2')
    {
      $emailTemplate->setToEmail('abc@gmail.com');
    }

    elseif($chk_sku == '3')
    {
      $emailTemplate->setToEmail('xyz@gmail.com');    
    }

    elseif($chk_sku == '4')
    {
      $emailTemplate->setToEmail('qwe@gmail.com');    
    }

    else{
      $emailTemplate->setToEmail('ewq@gmail.com');
    }

    try{
    return $emailTemplate->send();
    Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
  }

  catch (Exception $e) {
    Mage::getSingleton('core/session')->addError($e->getMessage());
  }

  }



}

?>

Error :

As per my condition if sku start with 2 mail should go to abc@gmail.com but here mail received ewq@gmail.com (Final email id in my if condition). How to correct my script?

How to solve the error?

When you echo $sku; inside your function, what does it show?

For my clarity may i know which function you asking about, sendMail() or sendMailbasedOnSku()?

You don’t pass $sku into sendMail(), so it is sendmailbasedonsku() that I am asking about.

Updated Code :

<?php
class Gta_MerchantNotification_Model_Observer {
  public function merchantremainder($Observer) {
    $order = $Observer->getEvent()->getOrder();
    $order_details = $order->getAllVisibleItems();

    $itemData = array();
    foreach ($order_details as $list) {
      $incrementid = $order->getIncrementId();
      $sku = $list->getsku();
      $name = $list->getName();
      $price = $list->getPrice();
      $Qty = $list->getQtyOrdered();

      $this->sendMailbasedOnSku($sku);

      $message = "<tr>
      <!-- <td>$incrementid</td> -->
      <td>$sku</td>
      <td>$name</td>
      <td>$price</td>
      <td>$Qty</td>
      </tr>";

      $itemData[$list->getId()] = $message;

    }

    $finalMessage = "
    <p>Order Id : $incrementid</p>
    <table border='1'>
    <tr>
    <!-- <th>Id</th> -->
    <th>Sku</th>
    <th>Product name</th>
    <th>Price</th>
    <th>Qty Ordered</th>
    </tr>";

    if (!empty($itemData)) {
      foreach ($itemData as $data) {
        $finalMessage .= $data;
      }

      $finalMessage .= "</table>";

      $this->sendMail($finalMessage);

    }

  }

  public function sendMail($message) {

    $body = "$message";
    $emailTemplate = Mage::getModel('core/email');
    $emailTemplate->setFromName('Test mail');
    $emailTemplate->setBody($body);
    $emailTemplate->setSubject("Custom Email from observer");
    $emailTemplate->setType('html');
    // $emailTemplate->setToEmail('abc@gmail.com');


    // if($sku == '2')
    // {
    //   $emailTemplate->setToEmail('abc@gmail.com');
    // }

    // elseif($sku == '3')
    // {
    //   $emailTemplate->setToEmail('xyz@gmail.com');    
    // }

    // elseif($sku == '4')
    // {
    //   $emailTemplate->setToEmail('qwe@gmail.com');    
    // }

    // else
    // {
    //   $emailTemplate->setToEmail('ewq@gmail.com');
    // }



    // $emailTemplate->send();
    
    // Mage::log('line no.91 - '. $sku,null,'sku_print.log',true);

  }



  public function sendMailbasedOnSku()
  {



    $chk_sku=(int)substr($sku, 0, 1);

    $emailTemplate = Mage::getModel('core/email');

    if($chk_sku == '2')
    {
      $emailTemplate->setToEmail('abc@gmail.com');
    }

    elseif($chk_sku == '3')
    {
      $emailTemplate->setToEmail('xyz@gmail.com');    
    }

    elseif($chk_sku == '4')
    {
      $emailTemplate->setToEmail('qwe@gmail.com');    
    }

    else{
      $emailTemplate->setToEmail('ewq@gmail.com');
    }

    try{
    return $emailTemplate->send();
    Mage::getSingleton('core/session')->addSuccess('Success message');
  }catch (Exception $e)
  {
    Mage::getSingleton('core/session')->addError($e->getMessage());
  }

  }



}

?>

Mail not received.

So you’ve gone from not receiving the email at the correct address, to not receiving it at all?

I notice that in sendmail() you do lots of stuff with $emailTemplate such as setting the body and subject, but you don’t do that in the longer function. Could that be related?

What about the value of $sku? What was it inside the function?

Updated code :

<?php
class Gta_MerchantNotification_Model_Observer {
  public function merchantremainder($Observer) {
    $order = $Observer->getEvent()->getOrder();
    $order_details = $order->getAllVisibleItems();

    $itemData = array();
    foreach ($order_details as $list) {
      $incrementid = $order->getIncrementId();
      $sku = $list->getsku();
      $name = $list->getName();
      $price = $list->getPrice();
      $Qty = $list->getQtyOrdered();

      $this->sendMailbasedOnSku($sku);

      $message = "<tr>
      <!-- <td>$incrementid</td> -->
      <td>$sku</td>
      <td>$name</td>
      <td>$price</td>
      <td>$Qty</td>
      </tr>";

      $itemData[$list->getId()] = $message;

    }

    $finalMessage = "
    <p>Order Id : $incrementid</p>
    <table border='1'>
    <tr>
    <!-- <th>Id</th> -->
    <th>Sku</th>
    <th>Product name</th>
    <th>Price</th>
    <th>Qty Ordered</th>
    </tr>";

    if (!empty($itemData)) {
      foreach ($itemData as $data) {
        $finalMessage .= $data;
      }

      $finalMessage .= "</table>";

      $this->sendMailbasedOnSku($finalMessage);

    }

  }


  public function sendMailbasedOnSku($message)
  {
    $body = "$message";
    $emailTemplate = Mage::getModel('core/email');
    $emailTemplate->setFromName('Test mail');
    $emailTemplate->setBody($body);
    $emailTemplate->setSubject("Custom Email from observer");
    $emailTemplate->setType('html');


    $chk_sku=(int)substr($sku, 0, 1);

    $emailTemplate = Mage::getModel('core/email');

    if($chk_sku == '2')
    {
      $emailTemplate->setToEmail('abc@gmail.com');
    }

    elseif($chk_sku == '3')
    {
      $emailTemplate->setToEmail('xyz@gmail.com');    
    }

    elseif($chk_sku == '4')
    {
      $emailTemplate->setToEmail('qwe@gmail.com');    
    }

    else{
      $emailTemplate->setToEmail('ewq@gmail.com');
    }

    try{
      $emailTemplate->send();
      Mage::getSingleton('core/session')->addSuccess('Success message');
    }catch (Exception $e)
    {
      Mage::getSingleton('core/session')->addError($e->getMessage());
    }
  }
}
?>

Anything wrong?

What happens when you test it?

But, yes, things wrong. In here:

public function sendMailbasedOnSku($message)
...
$chk_sku=(int)substr($sku, 0, 1);

where do you get $sku from? You’re not passing it in to the function.

$sku return : Line no: 94 33 (Log message see line public function sendMailbasedOnSku($sku) )

FYI : 33 is my product sku

<?php
class Gta_MerchantNotification_Model_Observer {
  public function merchantremainder($Observer) {
    $order = $Observer->getEvent()->getOrder();
    $order_details = $order->getAllVisibleItems();

    $itemData = array();
    foreach ($order_details as $list) {
      $incrementid = $order->getIncrementId();
      $sku = $list->getsku();
      $name = $list->getName();
      $price = $list->getPrice();
      $Qty = $list->getQtyOrdered();

      $this->sendMailbasedOnSku($sku);

      $message = "<tr>
      <!-- <td>$incrementid</td> -->
      <td>$sku</td>
      <td>$name</td>
      <td>$price</td>
      <td>$Qty</td>
      </tr>";

      $itemData[$list->getId()] = $message;

    }

    $finalMessage = "
    <p>Order Id : $incrementid</p>
    <table border='1'>
    <tr>
    <!-- <th>Id</th> -->
    <th>Sku</th>
    <th>Product name</th>
    <th>Price</th>
    <th>Qty Ordered</th>
    </tr>";

    if (!empty($itemData)) {
      foreach ($itemData as $data) {
        $finalMessage .= $data;
      }

      $finalMessage .= "</table>";

      $this->sendMail($finalMessage);

    }

  }

  public function sendMail($message) {

    $body = "$message";
    $emailTemplate = Mage::getModel('core/email');
    $emailTemplate->setFromName('GIRI Test mail');
    $emailTemplate->setBody($body);
    $emailTemplate->setSubject("Custom Email from observer");
    $emailTemplate->setType('html');
    // $emailTemplate->setToEmail('abc@gmail.com');

    if($sku == '2')
    {
      $emailTemplate->setToEmail('abc@gmail.com');
   
    }

    elseif($sku == '3')
    {
      $emailTemplate->setToEmail('xyz@gmail.com');  
    
    }

    elseif($sku == '4')
    {
      $emailTemplate->setToEmail('qwe@gmail.com');   
    }

    else
    {
      $emailTemplate->setToEmail('ewq@gmail.com');
    }

    $emailTemplate->send();
  }


  public function sendMailbasedOnSku($sku)
  {

    Mage::log('Line no: 94 '. $sku,null,'test_sku.log',true);

    $chk_sku=(int)substr($sku, 0, 1);

    $emailTemplate = Mage::getModel('core/email');

    if($chk_sku == '2')
    {
      $emailTemplate->setToEmail('abc@gmail.com');
    }

    elseif($chk_sku == '3')
    {
      $emailTemplate->setToEmail('xyz@gmail.com');    
    }

    elseif($chk_sku == '4')
    {
      $emailTemplate->setToEmail('qwe@gmail.com');    
    }

    else{
      $emailTemplate->setToEmail('ewq@gmail.com');
    }

    try{
      return $emailTemplate->send();
      Mage::getSingleton('core/session')->addSuccess('Success message');
    }catch (Exception $e)
    {
      Mage::getSingleton('core/session')->addError($e->getMessage());
    }
  }
}

?>

You just seem to be adding and removing blocks of code randomly now. You’ve removed all the extra code that sets the email body, from-address, subject and so on.

What happens when you run this code? Get no email anywhere? Get an email but to the wrong address?

As per my script :

 elseif($chk_sku == '3')
    {
      $emailTemplate->setToEmail('xyz@gmail.com');    
    }

I have placed ordered with sku 33, so that i have received mail in xyz@gmail but the empty message received. And i received a complete message in last mail id of the if condition ewq@gmail.com

What i need to do?