JSON response from API could not be parsed in Hook code for email newsletter

I’m trying to establish a mail alert, whenever an article is updated, using the page.update:after hook. When I’m saving an update to an article I always get:

Das Formular konnte nicht gespeichert werden
Exception: undefined. The JSON response from the API could not be parsed. Please check your API connection.

I’ve tried with two different mail servers. They both work when not used in a hook. Updated to Kirby 3.4 as I have read in other posts this would solve the JSON API Problem. Unfortunately did not for me. I have no clue what the problem is. Any hints?

This is my hook code (tried in config and as plugin, same result):

'hooks' => [
        'page.update:after' => function($newPage, $oldPage){
        $p = $newPage;
        if($p->template()=='article' && $p->isListed()) {
            $emailText = "some Text here ";
            $kirby = kirby();
            $bccarray = array();
            foreach($kirby->users() as $theUser){
              if(($theUser->notifyme() == 'true'))  {
                if(V::email($theUser->email())) {$bccarray[]=$theUser->email();};
                if(V::email($theUser->email2())) {$bccarray[]=$theUser->email2();};
              };
            };

          try {
                  $kirby->email(array(
                    'from'    => 'aktuelles@mydomain.de',
                    'to'      => 'webmaster@mydomain.de',
                    'bcc'     => $bccarray,
                    'subject' => 'A new message has been created',
                    'body'    => $emailText,
                  ));

        } //try
        catch(Exception $e) {
          echo $e->getMessage();
          }
        }  //if template
      } //Hook function code
      ]//hooks

Have you tested if sending the email works out of the hook context?

You cannot echo anything from your hook, this would lead to the error you get if something goes wrong. Throw an exception instead:

catch(Exception $e) {
  throw new Exception($e->getMessage());

}

Dear Sonja,

thanks for this advice in development methodology for hooks. It helped!

Just for reference, it was a simple error: $theUser->email() (built in variable/field) returns a string, $theUser->email2() (which is a custom user field of mine) returns an object. So $theUser->email2()->toString() did the trick.

Thanks again
Matthias