Laravel 即使抄送和密件抄送为空也发送邮件

Laravel Mail send even if cc and bcc is null

我laravel有邮件发送功能

public static function Compose($to,$cc,$bcc,$subject,$body)
    {

        // return $to;
        try
        {
            $data = [
                'body' => $body
            ];

            if(env('APP_ENV') == "local") 
            {
                $email["subject"] = $subject;
                $email["to"] = $to;
                $email["cc"] = $cc;
                $email["bcc"] = $bcc;
                Mail::send('email.composeMail', $data, function ($message) use ($email) {

                    $message
                        ->subject($email["subject"])
                        ->to($email["to"]);
                        ->cc($email["cc"]);
                        ->bcc($email["bcc"]);
                });
            }
            else
            {
                $email["subject"] = $subject;
                $email["to"] = $to;
                $email["cc"] = $cc;
                $email["bcc"] = $bcc;

                Mail::send('email.composeMail', $data, function ($message) use ($email) {

                    $message
                        ->subject($email["subject"])
                        ->to($email["to"]);
                        ->cc($email["cc"]);
                        ->bcc($email["bcc"]);
                });
            }
        } 
        catch (\Exception $e) 
        {
            Log::critical('Critical error occurred upon processing the transaction in Email.php -> Email class -> RevertPropertyToInbox method');
            throw new CustomErrorHandler($e->getMessage(),Constant::LogLevelCritical);
        }
    }

很多情况下CC和BCC为Null。 但是邮件没有发送,我收到错误消息

在这里,我想按原样使用代码,而不检查 CC 或 BCC 是否为空,是否有任何遗漏,以便我可以实现我的计划。

如果电子邮件地址为空,您将无法发送电子邮件,它总是会抛出错误

相反,您需要检查然后相应地发送电子邮件

试试这个

if($email["cc"] =='' && $email["bcc"] == ''){
 $message
                        ->subject($email["subject"])
                        ->to($email["to"]);
}
elseif($email["cc"] ==''){
$message
                        ->subject($email["subject"])
                        ->to($email["to"])
                        ->bcc($email["bcc"]);
}
else{

$message
                        ->subject($email["subject"])
                        ->to($email["to"])
                        ->cc($email["cc"]);

}

这些方法都可以用数组而不是纯字符串来调用 (docs)。在这种情况下,您应该能够将数组留空。试试这个:

$message
    ->subject($email["subject"])
    ->to($email["to"]);
    ->cc($email["cc"] ?: []);
    ->bcc($email["bcc"] ?: []);