Почему приведение null к массиву выходит из кода? - PullRequest
0 голосов
/ 24 февраля 2020
public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null)
    {
        $failedRecipients = (array) $failedRecipients;

        if (!$this->transport->isStarted()) {
            $this->transport->start();
        }

        $sent = 0;

        try {
            $sent = $this->transport->send($message, $failedRecipients);
        } catch (Swift_RfcComplianceException $e) {
            foreach ($message->getTo() as $address => $name) {
                $failedRecipients[] = $address;
            }
        }

        return $sent;
    }

Это код от поставщика / swiftmailer / swiftmailer / lib / classes / Swift / Mailer. php

Сначала он работал нормально, также у нас есть другой проект, в котором используется та же библиотека и он отлично работает в этом проекте. Но в одном проекте в строке

$failedRecipients = (array) $failedRecipients;

это не дает никакой ошибки, просто действует так, как если бы эта строка вызывала возврат из функции. И поэтому электронная почта не отправляется. $ failedRecipients имеет значение null.

Php версия - 7.2.26, и она должна нормально работать, в другом проекте она такая же.

Обновление

Информация, запрошенная Zelay'da:

$ сообщение это :. enter image description here

$ адрес будет строкой адреса электронной почты, имя будет нулевым, если код придет туда. Я взял их из $ message-> getTo (). Транспортным объектом является поставщик / swiftmailer / swiftmailer / lib / classes / Swift / Transport / SpoolTransport. php

Полный класс:

<?php

/*
 * This file is part of SwiftMailer.
 * (c) 2004-2009 Chris Corbyn
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Swift Mailer class.
 *
 * @author Chris Corbyn
 */
class Swift_Mailer
{
    /** The Transport used to send messages */
    private $transport;

    /**
     * Create a new Mailer using $transport for delivery.
     */
    public function __construct(Swift_Transport $transport)
    {
        $this->transport = $transport;
    }

    /**
     * Create a new class instance of one of the message services.
     *
     * For example 'mimepart' would create a 'message.mimepart' instance
     *
     * @param string $service
     *
     * @return object
     */
    public function createMessage($service = 'message')
    {
        return Swift_DependencyContainer::getInstance()
            ->lookup('message.'.$service);
    }

    /**
     * Send the given Message like it would be sent in a mail client.
     *
     * All recipients (with the exception of Bcc) will be able to see the other
     * recipients this message was sent to.
     *
     * Recipient/sender data will be retrieved from the Message object.
     *
     * The return value is the number of recipients who were accepted for
     * delivery.
     *
     * @param array $failedRecipients An array of failures by-reference
     *
     * @return int The number of successful recipients. Can be 0 which indicates failure
     */
    public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null)
    {
        $failedRecipients = (array) $failedRecipients;

        if (!$this->transport->isStarted()) {
            $this->transport->start();
        }

        $sent = 0;

        try {
            $sent = $this->transport->send($message, $failedRecipients);
        } catch (Swift_RfcComplianceException $e) {
            foreach ($message->getTo() as $address => $name) {
                $failedRecipients[] = $address;
            }
        }

        return $sent;
    }

    /**
     * Register a plugin using a known unique key (e.g. myPlugin).
     */
    public function registerPlugin(Swift_Events_EventListener $plugin)
    {
        $this->transport->registerPlugin($plugin);
    }

    /**
     * The Transport used to send messages.
     *
     * @return Swift_Transport
     */
    public function getTransport()
    {
        return $this->transport;
    }
}

1 Ответ

1 голос
/ 24 февраля 2020

SwiftMailer знает, каким получателям не удалось, но Laravel не раскрывает связанный параметр, чтобы помочь нам получить эту информацию:

/**
 * Send the given Message like it would be sent in a mail client.
 *
 * All recipients (with the exception of Bcc) will be able to see the other
 * recipients this message was sent to.
 *
 * Recipient/sender data will be retrieved from the Message object.
 *
 * The return value is the number of recipients who were accepted for
 * delivery.
 *
 * @param array $failedRecipients An array of failures by-reference
 *
 * @return int The number of successful recipients. Can be 0 which indicates failure
 */

public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null)
{
    $failedRecipients = (array) $failedRecipients;

    // FIXME: to be removed in 7.0 (as transport must now start itself on send)
    if (!$this->transport->isStarted()) {
        $this->transport->start();
    }

    $sent = 0;

    try {
        $sent = $this->transport->send($message, $failedRecipients);
    } catch (Swift_RfcComplianceException $e) {
        foreach ($message->getTo() as $address => $name) {
            $failedRecipients[] = $address;
        }
    }

    return $sent;
}

Вы можете получить доступ к ошибочным получателям для ошибок, используя Mail::failures()

if(count(Mail::failures()) > 0){
                //$errors = 'Failed to send confirmation email, please try again.';
                $message = "Email not send";
            }
return $message;

Вот полный класс: https://github.com/swiftmailer/swiftmailer/blob/master/lib/classes/Swift/Mailer.php

Swiftmailer заботится только о том, чтобы передать письмо на почтовый сервер.

Все остальное не имеет отношения к Swiftmailer, см. Здесь для Отказ обработки электронной почты с PHP?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...