Search code examples
phpsymfonyemailmessage

Use symfony objects for sending Swift_message


I am trying to create an email that messages all users that are tied to a specific company. If I take the recipients array and add it to my email and test with a single email, I can see all of the user emails print out in the test email. When I try and pass that same recipients array into setTo instead of using a single to email address I get a message "Warning: Illegal offset type"

    $company = $this->getDoctrine()->getRepository('Bundle:Customer')->findOneBy(array('accountId' => $compare->getCustomerAccount()));

    $recipients = [];
    foreach($company->getUsers() as $user){
        array_push($recipients, $user);
    }
    array_push($recipients, $company->getCsr());

    $newComment = new Comment();
    $newComment->setDetails($comment);
    $newComment->setUser($this->getUser());

    $em = $this->getDoctrine()->getManager();
    $em->flush();

    $message = \Swift_Message::newInstance()
        ->setSubject($subject)
        ->setFrom($fromEmail)
        ->setTo($recipients)
        ->setBody(
            $this->renderView(
                'Bundle:Comment:email_users.html.twig', array(
                    'subject' => $subject,
                    'comment' => $comment,
                    'company' => $company,
                    'proof' => $proof
                )
            )
        )
        ->setContentType('text/html')
    ;
    $this->get('mailer')->send($message);

Solution

  • I added the following to my user class which extends BaseUser:

    /**
     * Sets the email.
     *
     * @return string
     */
    public function getEmail()
    {
        return parent::getEmail();
    }
    

    Then I was able to run getEmail on each user

    $recipients = [];
    foreach($company->getUsers() as $user){
        array_push($recipients, $user->getEmail());
    }
    array_push($recipients, $company->getCsr()->getEmail());
    

    Email was sent successfully!