Home > Software engineering >  Laravel how to get the email address using a listener
Laravel how to get the email address using a listener

Time:11-16

I'm trying to get the email address of the sender via an event listener. I am able to log them fine using the code below but I can't access it directly because it is set to private by Symfony. hence I get this error: "Cannot access private property Symfony\Component\Mime\Address::$address"

So my question is how can I get the sender's email since I need to filter them first?

Code:

public function handle(MessageSent $event){
      $message = $event->message;
      Log::info($message->getTo());//this logs the email
   }

Log Result:

array (
  0 => 
  Symfony\Component\Mime\Address::__set_state(array(
     'address' => '[email protected]',
     'name' => 'Name',
  )),
)

But if I try this code below to check the email individually:

public function handle(MessageSent $event){
      $message = $event->message;
      
      foreach( $message->getTo() as $email ){
      info($email->address);//returns an error
      }
   }

I get this error:

Cannot access private property Symfony\Component\Mime\Address::$address

And if I use this code below to see what's happening

public function handle(MessageSent $event){
      $message = $event->message;      
      foreach( $message->getTo() as $email ){
         print_r($email);
      }
   }

Then I get this result:

Symfony\Component\Mime\Address Object ( [address:Symfony\Component\Mime\Address:private] => [email protected] [name:Symfony\Component\Mime\Address:private] => )

CodePudding user response:

You can see that there is a getter method for most of the Mime values, as in your case for the address.

$email->getAddress();
  • Related