Swiftmailer - Uncaught Error: Call to undefined method Swift_SmtpTransport::newInstance()

点点圈 提交于 2021-01-21 06:52:29

问题


I'm trying to send email using the Swiftmailer.

I'm getting an Uncaught Error:

Call to undefined method Swift_SmtpTransport::newInstance().

Here is the code:

require_once 'swift/lib/swift_required.php';

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
      ->setUsername ('email@gmail.com')
      ->setPassword ('password');

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

$message = Swift_Message::newInstance('Weekly Hours')
       ->setFrom (array('email@gmail.com' => 'My Name'))
       ->setTo (array('email@hotmail.com' => 'Recipient'))
       ->setSubject ('Weekly Hours')
       ->setBody ('Test Message', 'text/html');

$result = $mailer->send($message);

Based on the above code, what would be causing that mistake?


回答1:


I'm not quite familiar with SwiftMailer, but from the brief overview of the error you provided, and their documentation page, I can suggest you to try using new operator. From the error, it's clear that Swift_SmtpTransport class doesn't have a newInstance method, so when you use it to create a new instance, it throws an error. Maybe try using this instead:

require_once 'swift/lib/swift_required.php';

$transport = new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl');
$transport->setUsername('email@gmail.com')->setPassword('password');

$mailer = new Swift_Mailer($transport);

$message = new Swift_Message('Weekly Hours');
$message
   ->setFrom(['email@gmail.com' => 'My Name'])
   ->setTo(['email@hotmail.com' => 'Recipient'])
   ->setSubject('Weekly Hours')
   ->setBody('Test Message', 'text/html');

$result = $mailer->send($message);

Edit: PHP Doesn't allow a direct method call after instantiating an object (without parenthesis). Thanks, Art Geigel.



来源:https://stackoverflow.com/questions/45226880/swiftmailer-uncaught-error-call-to-undefined-method-swift-smtptransportnewi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!