使用 symfony 对象发送 Swift_message

Use symfony objects for sending Swift_message

我正在尝试创建一封电子邮件,向与特定公司相关的所有用户发送消息。如果我将收件人数组添加到我的电子邮件中并使用一封电子邮件进行测试,我可以看到所有用户电子邮件都在测试电子邮件中打印出来。当我尝试将相同的收件人数组传递到 setTo 而不是使用单个电子邮件地址时,我收到一条消息 "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);

Se setTo accept an associative array with email and name (check here in the doc), 所以你应该修改你的代码:

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

希望对您有所帮助

发生错误,因为您试图使用 $user 对象数组而不是字符串关联数组来设置收件人。当尝试访问以对象或数组为索引的数组的索引时,您将看到该错误消息。

你的 $recipients 数组应该看起来更像 array('receiver@domain.org', 'other@domain.org' => 'A name') 你应该没问题。

您的代码可能如下所示:

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

我只是假设您的用户对象有一个 getter 方法 getEmail(),其中 returns 用户电子邮件地址作为字符串。

我将以下内容添加到我的用户 class 中,它扩展了 BaseUser:

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

然后我就可以运行获取每个用户的电子邮件

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

邮件发送成功!