是什么导致PHPMailer的$ mail-> send()返回false?

时间:2018-12-10 13:27:25

标签: php phpmailer

看看下面的代码,我们什么时候才能进入else块?

<?php
  try {
    if ($mail->send()) {
      echo 'success';
    } else {
      echo 'failed to send';
      echo $mail->ErrorInfo;
    }
  } catch (Exception $e) {
    echo 'Exception!';
    echo $mail->ErrorInfo;
  }
?>

根据我的测试,电子邮件设置的配置出现任何问题(例如主机或端口错误,试图从foo@example.com发送),都会导致异常。

因此,我想知道是否有任何理由测试$mail->send()。还是可以假设如果没有异常发生,$mail->send()将返回true?

2 个答案:

答案 0 :(得分:3)

来自source

/**
 * Create a message and send it.
 * Uses the sending method specified by $Mailer.
 *
 * @throws Exception
 *
 * @return bool false on error - See the ErrorInfo property for details of the error
 */
public function send()
{
    try {
        if (!$this->preSend()) {
            return false;
        }
        return $this->postSend();
    } catch (Exception $exc) {
        $this->mailHeader = '';
        $this->setError($exc->getMessage());
        if ($this->exceptions) {
            throw $exc;
        }
        return false;
    }
}

preSend()方法:

/**
     * Prepare a message for sending.
     *
     * @throws Exception
     *
     * @return bool
     */
    public function preSend()
    {
        if ('smtp' == $this->Mailer or
            ('mail' == $this->Mailer and stripos(PHP_OS, 'WIN') === 0)
        ) {
            //SMTP mandates RFC-compliant line endings
            //and it's also used with mail() on Windows
            static::setLE("\r\n");
        } else {
            //Maintain backward compatibility with legacy Linux command line mailers
            static::setLE(PHP_EOL);
        }
        //Check for buggy PHP versions that add a header with an incorrect line break
        if (ini_get('mail.add_x_header') == 1
            and 'mail' == $this->Mailer
            and stripos(PHP_OS, 'WIN') === 0
            and ((version_compare(PHP_VERSION, '7.0.0', '>=')
                    and version_compare(PHP_VERSION, '7.0.17', '<'))
                or (version_compare(PHP_VERSION, '7.1.0', '>=')
                    and version_compare(PHP_VERSION, '7.1.3', '<')))
        ) {
            trigger_error(
                'Your version of PHP is affected by a bug that may result in corrupted messages.' .
                ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' .
                ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.',
                E_USER_WARNING
            );
        }
        try {
            $this->error_count = 0; // Reset errors
            $this->mailHeader = '';
            // Dequeue recipient and Reply-To addresses with IDN
            foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
                $params[1] = $this->punyencodeAddress($params[1]);
                call_user_func_array([$this, 'addAnAddress'], $params);
            }
            if (count($this->to) + count($this->cc) + count($this->bcc) < 1) {
                throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL);
            }
            // Validate From, Sender, and ConfirmReadingTo addresses
            foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) {
                $this->$address_kind = trim($this->$address_kind);
                if (empty($this->$address_kind)) {
                    continue;
                }
                $this->$address_kind = $this->punyencodeAddress($this->$address_kind);
                if (!static::validateAddress($this->$address_kind)) {
                    $error_message = sprintf('%s (%s): %s',
                        $this->lang('invalid_address'),
                        $address_kind,
                        $this->$address_kind);
                    $this->setError($error_message);
                    $this->edebug($error_message);
                    if ($this->exceptions) {
                        throw new Exception($error_message);
                    }
                    return false;
                }
            }
            // Set whether the message is multipart/alternative
            if ($this->alternativeExists()) {
                $this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE;
            }
            $this->setMessageType();
            // Refuse to send an empty message unless we are specifically allowing it
            if (!$this->AllowEmpty and empty($this->Body)) {
                throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
            }
            //Trim subject consistently
            $this->Subject = trim($this->Subject);
            // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
            $this->MIMEHeader = '';
            $this->MIMEBody = $this->createBody();
            // createBody may have added some headers, so retain them
            $tempheaders = $this->MIMEHeader;
            $this->MIMEHeader = $this->createHeader();
            $this->MIMEHeader .= $tempheaders;
            // To capture the complete message when using mail(), create
            // an extra header list which createHeader() doesn't fold in
            if ('mail' == $this->Mailer) {
                if (count($this->to) > 0) {
                    $this->mailHeader .= $this->addrAppend('To', $this->to);
                } else {
                    $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
                }
                $this->mailHeader .= $this->headerLine(
                    'Subject',
                    $this->encodeHeader($this->secureHeader($this->Subject))
                );
            }
            // Sign with DKIM if enabled
            if (!empty($this->DKIM_domain)
                and !empty($this->DKIM_selector)
                and (!empty($this->DKIM_private_string)
                    or (!empty($this->DKIM_private)
                        and static::isPermittedPath($this->DKIM_private)
                        and file_exists($this->DKIM_private)
                    )
                )
            ) {
                $header_dkim = $this->DKIM_Add(
                    $this->MIMEHeader . $this->mailHeader,
                    $this->encodeHeader($this->secureHeader($this->Subject)),
                    $this->MIMEBody
                );
                $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . static::$LE .
                    static::normalizeBreaks($header_dkim) . static::$LE;
            }
            return true;
        } catch (Exception $exc) {
            $this->setError($exc->getMessage());
            if ($this->exceptions) {
                throw $exc;
            }
            return false;
        }
    }

简而言之:如果发生异常,它将返回false。

答案 1 :(得分:0)

测试$mail->send()始终是一个好习惯。

要回答您的问题:

您是正确的。如果没有例外,那么它将始终返回true。

一些其他信息:

如果要在将电子邮件发送给收件人之前先对其进行测试,则可以执行以下操作:

您可以将php ini中的sendmail_path设置为所需的值。例如,它可以是tee -a mail.log,以便所有内容都记录到文件中。