Mentos93 Mentos93 - 3 months ago 11
PHP Question

Swiftmailer complain when 'cc' is empty

I use one function to send emails on two different places. On one place I need to cc another email address, and the other place it's not necessary, so I would think to keep cc by default on null, and when necessary insert an email address.

This is my function;

private function notifyByMail($to, $from, $toName="", $fromName="", $body, $subject, $cc="", $ccName="")
{
//use custom data to send notification email
$message = \Swift_Message::newInstance()
->setSubject($subject)
->setTo(array($to => $toName))
->setCc(array($cc => $ccName))
->setFrom(array($from => $fromName))
->setBody($body);

$this->get('mailer')->send($message);
}


And calling it on two different places like this;

$this->notifyByMail($to, $from, '', $name, $body, $subject);


and

$this->notifyByMail($to, $from, 'Jack', $name, $body, $subject, $cc, 'Jack');


The second one works because the cc isn't empty, but the first one has a problem. This is what the error is about;


An exception has occured: Address in mailbox given [] does not comply
with RFC 2822, 3.6.2.


I have removed the cc and test the first one again, and then it works perfectly. I need that cc, because on another place I use it. Can somebody please tell me why the cc can't be null? How should I fix this?

Answer

First of all, cc is not null but the empty string "". Second, why not use the trivial solution?

private function notifyByMail($to, $from, $toName="", $fromName="", $body, $subject, $cc="", $ccName="")
{
    //use custom data to send notification email
    $message = \Swift_Message::newInstance()
        ->setSubject($subject)
        ->setTo(array($to => $toName))
        ->setFrom(array($from => $fromName))
        ->setBody($body);            
    if(!empty($cc)){
        $message->setCc(array($cc => $ccName))
    }

    $this->get('mailer')->send($message);
}