Laravel 5和PHPMailer

Sas*_*Sam 13 php phpmailer laravel-5

有没有人有一个工作示例如何在Laravel 5中使用PHPMailer?在Laravel 4中,它使用起来很安静,但同样的方法在L5中不起作用.这是我在L4中所做的:

添加于composer.json:

"phpmailer/phpmailer": "dev-master",
Run Code Online (Sandbox Code Playgroud)

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) {
  .
  .
}
Run Code Online (Sandbox Code Playgroud)

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

sho*_*ild 10

好吧,我认为有多个错误......这是在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');
Run Code Online (Sandbox Code Playgroud)

当然,在将依赖项添加到composer.json之后,您需要进行作曲家更新

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


Nav*_*nDA 6

在 Laravel 5.5 或更高版本中,需要进行以下步骤

在你的 Laravel 应用程序上安装 PHPMailer。

composer require phpmailer/phpmailer
Run Code Online (Sandbox Code Playgroud)

然后转到您要使用 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';
        }
    }
}
Run Code Online (Sandbox Code Playgroud)