2017-05-03 28 views
1

我正在尝试创建一封电子邮件,用于向与特定公司绑定的所有用户发送邮件。如果我将收件人数组添加到我的电子邮件并使用一封电子邮件进行测试,则可以在测试电子邮件中看到所有用户电子邮件。当我尝试过的,而不是使用一个单一的电子邮件地址,我得到一个消息同一收件人数组setTo“警告:非法偏移类型”使用symfony对象发送Swift_message

$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); 
+1

看起来你在推用户对象而不是电子邮件地址? – ccKep

+0

@ccKep yup,如何访问symfony用户对象的电子邮件? getEmail不是一个函数。 –

+0

那么,如果您打算向他们发送邮件,您必须将电子邮件存储在某个地方?你的用户实体是什么样的? – ccKep

回答

0

我增加了以下内容延伸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()); 

电子邮件发送成功运行getEmail!

+0

第一部分已经过时了,如果你没有定义这个函数(并且你的基类没有,并且它是公共的 - 它在FOSUserBundle中),它就会被调用。很高兴你的工作虽然! – ccKep

+0

这就是我所假设的,但我最初尝试getEmail(),它说它不是一个函数 –

1

硒setTo接受电子邮件和名称(关联数组检查here在doc),所以你应该有类似修改代码:

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

希望这有助于

1

出现的错误,因为你想用的阵列设置收件人对象而不是字符串的关联数组。当试图以对象或数组作为索引访问数组的索引时,您将看到该错误消息。

你的$recipients数组应该看起来更像array('[email protected]', '[email protected]' => 'A name'),你应该没问题。

您的代码看起来是这样的:

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

我只是假设你的用户对象有一个getter方法getEmail()返回用户的电子邮件地址作为字符串。