Laravel 5 和 PHPMailer

Laravel 5 and PHPMailer

有没有人有我如何在 Laravel 5 中使用 PHPMailer 的工作示例?在 Laravel 4 中,它使用起来非常简单,但同样的方法在 L5 中不起作用。这是我在 L4 中所做的:

添加于composer.json

"phpmailer/phpmailer": "dev-master",

controller 中,我是这样使用它的:

$mail = new PHPMailer(true);
try {
  $mail->SMTPAuth(...);
  $mail->SMTPSecure(...);
  $mail->Host(...);
  $mail->port(...);

  .
  .
  .

  $mail->MsgHTML($body);
  $mail->Send();
} catch (phpmailerException $e) {
  .
  .
} catch (Exception $e) {
  .
  .
}

但它在 L5 中不起作用。任何的想法?谢谢!

好吧,我认为有很多错误... 这是 Laravel 5 中使用 PhpMailer 发送邮件的工作示例。刚刚测试过。

        $mail = new \PHPMailer(true); // notice the \  you have to use root namespace here
    try {
        $mail->isSMTP(); // tell to use smtp
        $mail->CharSet = "utf-8"; // set charset to utf8
        $mail->SMTPAuth = true;  // use smpt auth
        $mail->SMTPSecure = "tls"; // or ssl
        $mail->Host = "yourmailhost";
        $mail->Port = 2525; // most likely something different for you. This is the mailtrap.io port i use for testing. 
        $mail->Username = "username";
        $mail->Password = "password";
        $mail->setFrom("youremail@yourdomain.de", "Firstname Lastname");
        $mail->Subject = "Test";
        $mail->MsgHTML("This is a test");
        $mail->addAddress("recipient@anotherdomain.de", "Recipient Name");
        $mail->send();
    } catch (phpmailerException $e) {
        dd($e);
    } catch (Exception $e) {
        dd($e);
    }
    die('success');

当然,您需要在将依赖项添加到 composer.json

后进行作曲家更新

但是,我更喜欢内置于 SwiftMailer 中的 laravel。 http://laravel.com/docs/5.0/mail

在Laravel 5.5以上,需要进行以下步骤

在您的 laravel 应用程序上安装 PHPMailer。

composer require phpmailer/phpmailer

然后转到您要使用 phpmailer 的控制器。

<?php
namespace App\Http\Controllers;

use PHPMailer\PHPMailer;

class testPHPMailer extends Controller
{
    public function index()
    {
        $text             = 'Hello Mail';
        $mail             = new PHPMailer\PHPMailer(); // create a n
        $mail->SMTPDebug  = 1; // debugging: 1 = errors and messages, 2 = messages only
        $mail->SMTPAuth   = true; // authentication enabled
        $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
        $mail->Host       = "smtp.gmail.com";
        $mail->Port       = 465; // or 587
        $mail->IsHTML(true);
        $mail->Username = "testmail@gmail.com";
        $mail->Password = "testpass";
        $mail->SetFrom("testmail@gmail.com", 'Sender Name');
        $mail->Subject = "Test Subject";
        $mail->Body    = $text;
        $mail->AddAddress("testreciver@gmail.com", "Receiver Name");
        if ($mail->Send()) {
            return 'Email Sended Successfully';
        } else {
            return 'Failed to Send Email';
        }
    }
}