# Problem with event onEmailGenerate

**URL:** <https://forum.mautic.org/t/problem-with-event-onemailgenerate/3391>\
**Category:** Development\
**Created:** [February 4, 2016, 8:21pm UTC](https://forum.mautic.org/t/problem-with-event-onemailgenerate/3391 "2016-02-04T20:21:08Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![natansouzag](https://avatars.discourse-cdn.com/v4/letter/n/db5fbb/32.png) [@natansouzag](https://forum.mautic.org/u/natansouzag)\
**Post date:** [February 4, 2016, 8:21pm UTC](https://forum.mautic.org/t/problem-with-event-onemailgenerate/3391/1 "2016-02-04T20:21:08Z")

</div>

I’m doing a plugin that accesses remote data to change a specific token at the email sending . The function is onEmailGenerate , but in this role I noticed that the mautic calls again for a different lead without even finished making the sending of the first email . Aparentente is a competition problem someone went through it ?  
  
  
  
Here is my source code:

Code:

\<?php namespace MauticPluginVestconBundleEventListener;

use MauticCoreBundleEventListenerCommonSubscriber;  
use MauticEmailBundleEmailEvents;  
use MauticEmailBundleEventEmailBuilderEvent;  
use MauticEmailBundleEventEmailSendEvent;

/\*\*

Class EmailSubscriber  
\*/  
class EmailSubscriber extends CommonSubscriber  
{

/\*\*

@return array _/ static public function getSubscribedEvents() { return array( EmailEvents::EMAIL\_ON\_BUILD =\> array(‘onEmailBuild’, 0), EmailEvents::EMAIL\_ON\_SEND =\> array(‘onEmailGenerate’, 0), EmailEvents::EMAIL\_ON\_DISPLAY =\> array(‘onEmailGenerate’, 0) ); }  
/_\*

@param EmailBuilderEvent $event _/ public function onEmailBuild(EmailBuilderEvent $event) { $content = $this-\>templating-\>render(‘VestconBundle:SubscribedEventsEmailToken:token.html.php’); $event-\>addTokenSection(‘vestcon.token’, ‘plugin.vestcon.builder.header’, $content); }  
/_\*

@param EmailSendEvent $event  
\*/  
public function onEmailGenerate(EmailSendEvent $event)  
{

$stringHtmlEmail = $this-\>getEmailDynamic($event);

// Set updated content  
$event-\>setContent($stringHtmlEmail);  
}

private function getEmailDynamic($event)  
{

$html = $content;

try {

```
$content = $event->getContent();

if (strpos($content, '{cart.model1}') == true) {
    $html = $this->getHtmlCart($event, '{cart.model1}');
}
else if(strpos($content, '{cart.model2}') == true) {
    $html = $this->getHtmlCart($event, '{cart.model2}');
}

```

}  
catch (Exception $ex ){ }

return $html;  
}

private function getHtmlCart($event, $token)  
{

// Get content  
$content = $event-\>getContent();

$lead = $event-\>getLead();  
$cartId = $lead[‘cart\_id’];

$urlServico = ‘[http://xxxxxx](http://xxxxxx)’;  
$json\_object = $this-\>getJson($urlServico, $cartId);

ob\_start();  
include (dirname( **DIR** ).’\Views\TemplateEmails\Cart’.str\_replace(array("{", “}”), “”, $token).’.html.php’);  
$stingEmail = ob\_get\_clean();

return str\_replace($token, $stingEmail, $content);  
}

private function getJson($url, $id)  
{  
$username = ‘xxxxxx’;  
$password = ‘xxxxxx’;

$postdata = http\_build\_query( array(‘cestaid’ =\> $id ) );

$opts = array(‘http’ =\>  
array(  
‘method’ =\> ‘POST’,  
‘header’ =\> “Content-Type: application/x-www-form-urlencodedrn”.  
“Authorization: Basic “.base64\_encode(”$username:$password”).“rn”,  
‘content’ =\> $postdata,  
‘timeout’ =\> 60  
)  
);

$context = stream\_context\_create($opts);

$unparsed\_json = file\_get\_contents($url, false, $context);

$unparsed\_json = mb\_convert\_encoding($unparsed\_json, ‘HTML-ENTITIES’, “UTF-8”);

$json\_object = json\_decode($unparsed\_json);

return $json\_object;  
}  
}

---

<div class="post-metadata">

**Author:** ![natansouzag](https://avatars.discourse-cdn.com/v4/letter/n/db5fbb/32.png) [@natansouzag](https://forum.mautic.org/u/natansouzag)\
**Post date:** [February 4, 2016, 8:21pm UTC](https://forum.mautic.org/t/problem-with-event-onemailgenerate/3391/2 "2016-02-04T20:21:08Z")

</div>

I’m doing a plugin that accesses remote data to change a specific token at the email sending . The function is onEmailGenerate , but in this role I noticed that the mautic calls again for a different lead without even finished making the sending of the first email . Aparentente is a competition problem someone went through it ?

Here is my source code:

```auto
<?php
namespace MauticPluginVestconBundleEventListener;

use MauticCoreBundleEventListenerCommonSubscriber;
use MauticEmailBundleEmailEvents;
use MauticEmailBundleEventEmailBuilderEvent;
use MauticEmailBundleEventEmailSendEvent;

/**

Class EmailSubscriber
*/
class EmailSubscriber extends CommonSubscriber
{

/**

@return array */ static public function getSubscribedEvents() { return array( EmailEvents::EMAIL_ON_BUILD => array('onEmailBuild', 0), EmailEvents::EMAIL_ON_SEND => array('onEmailGenerate', 0), EmailEvents::EMAIL_ON_DISPLAY => array('onEmailGenerate', 0) ); }
/**

@param EmailBuilderEvent $event */ public function onEmailBuild(EmailBuilderEvent $event) { $content = $this->templating->render('VestconBundle:SubscribedEventsEmailToken:token.html.php'); $event->addTokenSection('vestcon.token', 'plugin.vestcon.builder.header', $content); }
/**

@param EmailSendEvent $event
*/
public function onEmailGenerate(EmailSendEvent $event)
{

$stringHtmlEmail = $this->getEmailDynamic($event);

// Set updated content
$event->setContent($stringHtmlEmail);
}

private function getEmailDynamic($event)
{

$html = $content;

try {

    $content = $event->getContent();

    if (strpos($content, '{cart.model1}') == true) {
        $html = $this->getHtmlCart($event, '{cart.model1}');
    }
    else if(strpos($content, '{cart.model2}') == true) {
        $html = $this->getHtmlCart($event, '{cart.model2}');
    }

}
catch (Exception $ex ){ }

return $html;
}

private function getHtmlCart($event, $token)
{

// Get content
$content = $event->getContent();

$lead = $event->getLead();
$cartId = $lead['cart_id'];

$urlServico = 'http://xxxxxx';              
$json_object = $this->getJson($urlServico, $cartId);

ob_start();
include (dirname( __DIR__ ).'\Views\TemplateEmails\Cart\'.str_replace(array("{", "}"), "", $token).'.html.php');      
$stingEmail = ob_get_clean();

return str_replace($token, $stingEmail, $content);
}

private function getJson($url, $id)
{
$username = 'xxxxxx';
$password = 'xxxxxx';

$postdata = http_build_query( array('cestaid' => $id ) );

$opts = array('http' =>
        array(
                'method' => 'POST',
                'header' => "Content-Type: application/x-www-form-urlencodedrn".
                "Authorization: Basic ".base64_encode("$username:$password")."rn",
                'content' => $postdata,
                'timeout' => 60
        )
);

$context = stream_context_create($opts);

$unparsed_json = file_get_contents($url, false, $context);

$unparsed_json = mb_convert_encoding($unparsed_json, 'HTML-ENTITIES', "UTF-8");

$json_object = json_decode($unparsed_json);     

return $json_object;        
}
}
```

---

<div class="post-metadata">

**Author:** ![escopecz](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.mautic.org/escopecz/32/370_2.png) [@escopecz](https://forum.mautic.org/u/escopecz)\
**Post date:** [February 5, 2016, 11:32am UTC](https://forum.mautic.org/t/problem-with-event-onemailgenerate/3391/3 "2016-02-05T11:32:46Z")

</div>

I’m reading your code, but it is hard to comment on the lines since here are no line numbers. For example I don’t understand why you have `$html = $content;` before the $content var is created. Could you link to the GitHub repo with your plugin so we could comment on each line?
