Jump to content
aveeva

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

Recommended Posts

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 :

encLQH.jpg

 

If order placed mail send to abc@gmail.com.
How to set email sender 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 :

2aiBze.jpg

 

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

tmWfEx.jpg

 

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

M5dGIn.jpg

 

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.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Share this post


Link to post
Share on other sites

I'm not sure what you are asking. If I understand, simply convert the integer to a string (strval) then test the first character of that strnig and take the appropriate action.

Share this post


Link to post
Share on other sites

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

 

 

Share this post


Link to post
Share on other sites
1 hour ago, aveeva said:

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

Oh, I saw a thread about that a second ago...

Here. That looks like it talks about your question exactly.

Share this post


Link to post
Share on other sites

Seems like you need a couple of things

1 ) An array of email addresses (index = first digit of sku)

$addys = [ 2 => 'abc@gmail.com',
           3 => 'xyz@gmail.com',
           4 => 'qwe@gmail.com'
         ];

 

2 ) Alter the structure of your $itemData array to add the first digit of sku as a sub-index to separate each order into 3 groups

$itemData[$orderNo][$skuFirst] = $message;

 

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites
2 hours ago, aveeva said:

public function sendMailbasedOnSku($sku)

$emailTemplate has not been defined inside that function and is, therefore, null.

Share this post


Link to post
Share on other sites

@Barand After added $emailTemplate = Mage::getModel('core/email');  mail working, but if condition not working. 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?

Share this post


Link to post
Share on other sites

Final 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)
  {



    $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());
  }

  }



}

?>

 

Share this post


Link to post
Share on other sites

I suggested the $addys array to save you a lot of repetitive ifelse coding. Getting the email address to use becomes

$chk_sku=substr($sku, 0, 1);   
$sendTo = $addys[$chk_sku] ?? 'ewo@gmail.com';

 

Share this post


Link to post
Share on other sites

How to declare more than one mail id,

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

$sendTo = $addys[$chk_sku] ?? 'ewo@gmail.com';

Share this post


Link to post
Share on other sites
Posted (edited)

@Barand

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?

Edited by aveeva

Share this post


Link to post
Share on other sites
                            +---------------------+               
                            |                     |           Yes       
                            |    DOES IT WORK?    +-----------------------+
                            |                     |                       |
                            +----------+----------+                       |
                                       |                                  |
                                       |                                  |
                                       |  No                              |
                                       |                                  |
                                       |                                  |
                                       |                                  |
                            +---------------------+              +----------------+
                            |                     |              |                |
                            |  SOMETHING'S WRONG  |              |   PROBABLY OK  |
                            |                     |              |                |
                            +---------------------+              +----------------+
                            
 

 

Share this post


Link to post
Share on other sites

@Barand  here i can see only one mail id, 

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

$sendTo = $addys[$chk_sku] ?? 'ewo@gmail.com';

How to add more than one mail id?

Share this post


Link to post
Share on other sites

getting error,

 

<?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;
      $itemData[$orderNo][$skuFirst] = $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('GIRI Test mail');
    $emailTemplate->setBody($body);
    $emailTemplate->setSubject("Custom Email from observer");
    $emailTemplate->setType('html');



    
   $addys = [ 
          2 => 'jeevarathinamit@gmail.com',
          3 => 'aveevacool@gmail.com',
          4 => 'zus710@gmail.com'
         ];

    // CHECK SKU FIRST DIGIT

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



    if($chk_sku == '2')
    {
      $sendTo = $addys[$chk_sku] ?? 'jeevarathinamit@gmail.com';
    }

    elseif($chk_sku == '3')
    {
      $sendTo = $addys[$chk_sku] ?? 'aveevacool@gmail.com';   
    }

    elseif($chk_sku == '4')
    {
      $sendTo = $addys[$chk_sku] ?? 'zus710@gmail.com'; 

    }

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

  }
}

?>

 

Could you help me with above script.

Share this post


Link to post
Share on other sites
$addys = [ 
          2 => 'jeevarathinamit@gmail.com',
          3 => 'aveevacool@gmail.com',
          4 => 'zus710@gmail.com'
         ];

// CHECK SKU FIRST DIGIT
$chk_sku=(int)substr($sku, 0, 1);
// GET THE APPROPRIATE EMAIL ADDRESS
$sendTo = $addys[$chk_sku] ?? 'giriwebsiteonline@gmail.com';
// USE IT
$emailTemplate->setToEmail($sendTo);
return $emailTemplate->send();

 

Share this post


Link to post
Share on other sites

@Barand 

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;
      $itemData[$orderNo][$skuFirst] = $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');



    
   $addys = [ 
          2 => 'abc@gmail.com',
          3 => 'xyz@gmail.com',
          4 => 'qwe@gmail.com'
         ];

    // CHECK SKU FIRST DIGIT

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



    if($chk_sku == '2')
    {
      $sendTo = $addys[$chk_sku] ?? 'abc@gmail.com';
    }

    elseif($chk_sku == '3')
    {
      $sendTo = $addys[$chk_sku] ?? 'xyz@gmail.com';   
    }

    elseif($chk_sku == '4')
    {
      $sendTo = $addys[$chk_sku] ?? 'qwe@gmail.com'; 

    }

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

  }
}

?>

 

order not placed.

Share this post


Link to post
Share on other sites

Finally done with below script :

<?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);

      $this->sendMailbasedOnSku($finalMessage,$sku);

    }

  }

  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($message, $sku)
  {

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

    $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');
    }
      return $emailTemplate->send();

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

 

 

But few correction are there, how to solve below logic,

eg: If an order contains,  2 series of sku and 3 series of sku order mail received only by 3 series of sku mail not received 2 series of sku mail.

another eg. If order placed with 3 products,  sku- 22 (abc@gmail.com),  sku - 33 (xyz@gmail.com), sku -44 (qwe@gmail.com) order received only qwe@gmail.com

My condition, if the order contains 2 products means to send a separate mail.

 

like

2 series of sku :

2aiBze.jpg

 

3 series of sku :

tmWfEx.jpg

 

4 Series of sku :

M5dGIn.jpg

 

now order received highest value of sku,

 

6b051014490fb0b7e1b09f97d3a9b48b9b08ed90

 

Share this post


Link to post
Share on other sites

Your problems are mainly because you are trying to write code before you have learnt to read.

In my first post I said you needed 2 things.

  • The first you have totally disregarded despite my spoonfeeding you the required code.
  • The second addresses the problem you are now having and has also been ignored.

Good luck and goodbye.

  • Like 1

Share this post


Link to post
Share on other sites

One more attempt. Here's a script which puts the hints I gave you into practice. As you can see, it splits the ordered items into separate order depending on the SKU group

SAMPLE:

image.thumb.png.8a90a360d6a0600dc4ef7d71b688cd0e.png

Code (read, understand what's going on and learn. Refer to php.net manual if you don't know what something does.)

(Not an elseif()..elseif() to be found!)

<?php 
const HOST     = 'localhost';                                                                  #
const USERNAME = '????';                                                                       #
const PASSWORD = '????';                                                                       #
const DATABASE = '????';                                                                       #     These lines would
                                                                                               #
function pdoConnect($dbname=DATABASE)                                                          #     normally be in
{                                                                                              #
    $db = new PDO("mysql:host=".HOST.";dbname=$dbname;charset=utf8",USERNAME,PASSWORD);        #     an included file
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);                              #
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);                         #
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);                                      #
    return $db;                                                                                #
}                                                                                              #

$pdo = pdoConnect();

//
//  CREATE TEST DATA USED BY THIS EXAMPLE                                    
//
$pdo->exec("CREATE TABLE IF NOT EXISTS aveeva (
                id int not null auto_increment primary key,
                order_no int,
                sku int,
                product varchar(50),
                qty int
                )
            ");
$pdo->exec("REPLACE INTO aveeva (id, order_no, sku, product, qty) VALUES
                (1,1020345, 12345, 'Pair of left-footed socks', 2),
                (2,1020345, 35547, 'Square Hula hoop', 1),
                (3,1020345, 12346, 'Pair of right-footed socks', 2),
                (4,1020345, 62347, 'Pair of three-legged tights', 5),
                (5,1020345, 45501, 'String vest', 1),
                (6,1020345, 45501, 'Thermal long johns (red)', 2),
                (7,1020345, 22105, 'Staffordshire pot dog', 2),
                (8,1020345, 38962, '250 Kg dumbell set', 1),
                (9,1020345, 23176, 'Ming vase', 1),
                (10,1020345, 23194, 'Porcelain elephant', 1),
                (11,1020345, 38547, '0.5 metre yoga mat', 1)
            ");


                // DUMMY CLASS TO PROVIDE THE METHODS YOU USED
                class Magee                  
                {
                    private $fromName;
                    private $body;
                    private $subject;
                    private $type;
                    private $sendTo;
                    
                    public function __construct()
                    {
                    }
                    
                    public function setFromName($str)
                    {
                        $this->fromName = $str;
                    }
                    
                    public function setBody($str)
                    {
                        $this->body = $str;
                    }
                    
                    public function setSubject($str)
                    {
                        $this->subject = $str;
                    }
                    
                    public function setType($str)
                    {
                        $this->type = $str;
                    }
                    
                    public function setToEmail($str)
                    {
                        $this->sendTo = $str;
                    }
                    
                    public function send()
                    {
                        //
                        //  Instead of sending emails
                        //  we just build content
                        //  for demonstration output
                        //
                        $out = "<fieldset><legend>TO: {$this->sendTo}</legend>
                                    <label>From</label>{$this->fromName}<br>
                                    <label>Subject</label>{$this->subject}<br>
                                    {$this->body}<br>
                                    ";
                        $out .= "</fieldset>";
                        return $out;
                    }
                } #Magee

// define email addresses for the sku groups
const DEFAULT_ADDY = 'other@gmail.com';
$addys = [ 
          2 => 'abc@gmail.com',
          3 => 'xyz@gmail.com',
          4 => 'qwe@gmail.com'
         ];


$res = $pdo->query("SELECT sku
                         , product
                         , qty
                         , order_no 
                    FROM aveeva
                    ORDER BY order_no, sku     
                   ");
$orders = [];
//
//  Split the items for each order 
//  into groups depending the first
//  digit of their SKU
//
foreach ($res as $r) {
    $ono = array_pop($r);
    $sku1 = substr($r['sku'], 0, 1);
    if (!isset($addys[$sku1])) {
        $sku1 = 0;
    }
    $orders[$ono][$sku1][] = $r;
}

//
//  Build the email bodies from the array data
//
$emailsSent = '';
foreach ($orders as $ono => $odata) {
    
    foreach ($odata as $sku1 => $sdata) {
        $message = "<table border='1'>
                    <caption>Order No: $ono</caption>
                    <tr><th>SKU</th><th>Product</th><th>Quantity</th></tr>\n";
        foreach ($sdata as $item) {
            $message .= "<tr><td>" . join("</td><td>", $item) . "</td></tr>\n";
        }
        $message .= "</table>\n";
        
        $emailsSent .= sendMailbasedOnSku($message, $addys, $sku1);
    }
}


function sendMailbasedOnSku($message, $addys, $sku1)
{
    $emailTemplate = new Magee;
    $emailTemplate->setFromName('GIRI Test mail');
    $emailTemplate->setBody($message);
    $emailTemplate->setSubject("Custom Email from observer");
    $emailTemplate->setType('html');

    // GET THE APPROPRIATE EMAIL ADDRESS
    $sendTo = $addys[$sku1] ?? DEFAULT_ADDY;
    // USE IT
    $emailTemplate->setToEmail($sendTo);
    return $emailTemplate->send();
}
?>
<html>
<head>
<title>Example</title>
<style type='text/css'>
    body     { font-family: clibri, sans-serif; font-size: 11pt;}
    fieldset { width: 70%; margin: 16px auto; padding: 16px;}
    legend   { background-color: black; color: white; padding: 4px;}
    label    { display: inline-block; width: 120px; font-weight: 600;}
    table    { width: 50%; margin: 16px auto; border-collapse: collapse;}
    th       { background-color: black; color: white; padding: 8px;}
    td       { padding: 4px 8px;} 
</style>
</head>
<body>
    <?=$emailsSent?>
</body>
</html>

 

  • Thanks 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.