通过 PHP 和 Swiftmailer 从联系表单发送电子邮件时导致致命错误的原因是什么?

What is causing a Fatal Error when sending email from a contact form via PHP and Swiftmailer?

我是 Swiftmailer 的新手,正在尝试通过本地主机 (XAMPP) 上的 HTML 联系表发送邮件。按 'submit' 按钮后,错误显示为:

Fatal error: Class 'Swift_SmtpTransport' not found in /Applications/XAMPP/xamppfiles/htdocs/testsite/sendmessage.php on line 23

第 23、24 和 25 行是这一部分:

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, 'tls')
    ->setUsername('foobar@googlemail.com')
    ->setPassword('GENERATED PASSWORD');

我期待邮件在此时发送,并显示 'Mail Sent' 消息以及 PHP 文件中的回显行,但是当我看到 "Mail Sent" 确认我也遇到了错误,而且我没有收到电子邮件。

我查阅了文档 here,我在 'sendmessage.php' 中包含的代码似乎是正确的:

<?php
error_reporting(E_ALL);

echo getcwd();
echo function_exists('proc_open') ? "Yep, that will work" : "Sorry, that won't work";

require_once(dirname(__FILE__)."/swift.php");
echo 'Mail sent <br />';

// Grab the post data
$name = filter_var($_POST['Name'], FILTER_SANITIZE_STRING);
$usermail = filter_var($_POST['Email'], FILTER_SANITIZE_EMAIL);
$content = filter_var($_POST['Message'], FILTER_SANITIZE_STRING);

// Construct the body of the email
$data = "Name: " . $name . "<br />" . "Email: " . $usermail . "<br />" . "Message: " . $content;

// Create the transport
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, 'tls')
    ->setUsername('foobar@googlemail.com')
    ->setPassword('GENERATED PASSWORD');
echo 'line 26 <br />';

// Create the mailer using the created transport
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('This is the subject')
    ->setFrom(array('foobar@googlemail.com' => 'Feedback Received From User'))
    ->setTo(array('barfoo@gmail.com', 'foobar@googlemail.com' => 'Lead Recipients'))
    ->setSubject('Here is your Feedback subject')
    ->setBody($data, 'text/html');
echo 'line 34 <br />';

// Send the message
$result = $mailer -> send($message);
echo $result;
echo 'line 39<br />';
?>

proc_open returns a "Yep, that will work",但如上所述,我的收件箱中没有收到电子邮件。

我已尝试将相关线路上的端口更改为 25 和 486,但没有成功。

经过 Google 搜索后,我发现 似乎有同样的问题,但接受的答案并没有解决我的问题。

请注意,我有一个 关于联系表格错误的问题,这个问题是从那个问题开始的。

似乎 SwiftMailer 加载不正确或不完整。我不能保证它会有任何帮助,但请尝试以下操作:

将 GIT 克隆到源(html 或 htdocs)目录(参见 https://github.com/swiftmailer/swiftmailer/blob/5.x/doc/installing.rst)。

这应该为您提供一个名为 "swiftmailer" 的目录,并且您从中加载 swiftmailer 的脚本应该位于同一目录中。然后将 "require_once" 行更改为以下内容:

require_once("swiftmailer/lib/swift_required.php");

我只是粗略地浏览了 swiftmailer 的源代码,但如果我没记错的话它应该会自动为您完成剩下的工作,包括加载 Swift_SmtpTransport class。