在 zend 框架 2 中邮件传输失败时如何 return false?

how to return false when mail transport failed in zend framework 2?

如果邮件发送失败,我正在尝试 return fail 消息 json,这是我的代码:

$transport = new SmtpTransport();
            $options   = new SmtpOptions(array(
                    'name'              => 'localhost',
                    'host'              => 'localhost',
                    'connection_class'  => 'login',
                    'connection_config' => array(
                            'username' => 'cscsacsac',
                            'password' => 'csdca',
                            //'ssl'=>'ssl',
                            //'port' => '465',
                    ),
            ));

            $transport->setOptions($options);
            $sent = true;
            try {

                $transport->send($mail);
            }
            catch (\Zend\Mail\Transport\Exception\DomainException $e) {
                $sent = false;
            }

            if($sent){

                echo "success";

                exit;
            }

            elseif(!$sent){

                echo "fail";

                exit;
            }

这里是 ajax:

$.ajax({
          type: "POST",
          url: '<?php echo MAIN_URL?>cases',
          data: { name: name, email: email, mobile: mobile, address: address, compliant: compliant },
          success:function(data){

            if(data =='success'){

                $('.casesMailResponse').css({'color':'#00917D'});
                $('.casesMailResponse').html('Your case has been sent successfully.');
            }

            else if(data == 'fail'){

                $('.casesMailResponse').css({'color':'#F6565B'});
                $('.casesMailResponse').html('Some errors occurred, please try again.');
            }
          },
        });

但如果失败,我会因 Incorrect authentication data 而收到内部服务器错误,因此不会显示失败消息

你能试试吗:

 }
 catch (\Zend\Mail\Transport\Exception\DomainException $e) {
    $sent = false;
 } catch (Exception $e) {
    $sent = false;
}

只是猜测....

您只捕捉到 Zend\Mail\Transport\Exception\DomainException,但 SMTP 传输适配器也可以抛出其他异常。例如在 send 方法中它可以抛出 Zend\Mail\Transport\Exception\RuntimeException.

我建议捕获邮件包的异常接口:

    $sent = true;
    try {
        $transport->send($mail);
    } catch (\Zend\Mail\Transport\Exception\ExceptionInterface $e) {
        $sent = false;
    }