Php SwiftMailer,致命错误:对非对象调用成员函数Send()

Php SwiftMailer,致命错误:对非对象调用成员函数Send(),php,email,object,swiftmailer,Php,Email,Object,Swiftmailer,我正在尝试使用Swiftmailer发送电子邮件,但出现以下错误: 致命错误:对第20行x中的非对象调用成员函数send() 这是我的代码: <?php require_once('swift/lib/swift_required.php'); $to = $_POST['email']; if(empty($to)) { header("Location: index.php?error=empty"); } echo $to; $body="This is my mes

我正在尝试使用Swiftmailer发送电子邮件,但出现以下错误:

致命错误:对第20行x中的非对象调用成员函数send()

这是我的代码:

<?php

require_once('swift/lib/swift_required.php');

$to = $_POST['email'];
if(empty($to)) {
    header("Location: index.php?error=empty");
}

echo $to;

$body="This is my message!";

$message = Swift_Message::newInstance('Some subject')
    ->setFrom(array('example@example.com' => 'John Doe'))
    ->setTo($to)
    ->setBody($body);
$message->attach(Swift_Attachment::fromPath("myfile.pdf"));

$result = $mailer->send($message); // line 20

?>


有人能帮我吗?

错误表明$mailer对象从未创建过,因此您无法调用它上的任何对象。我相信您在第20行之前遗漏了类似的内容:

$transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25)
  ->setUsername('your username')
  ->setPassword('your password');

$mailer = Swift_Mailer::newInstance($transport);

在您的代码中,
$mailer
应该来自哪里…?