Laravel 5 and PHPMailer

Sas Sam picture Sas Sam · Apr 7, 2015 · Viewed 33.1k times · Source

Does anybody have a working example how I can work with PHPMailer in Laravel 5? In Laravel 4 it was quiet simple to use but the same method doesn't work in L5. Here it is what I did in L4:

Added in composer.json:

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

And in the controller I've used it like this:

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

  .
  .
  .

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

But it doesn't work in L5. Any idea? Thanks!

Answer

shock_gone_wild picture shock_gone_wild · Apr 7, 2015

Well there are multiple mistakes i think... This is a working example of sending mail with PhpMailer in Laravel 5. Just tested it.

        $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("[email protected]", "Firstname Lastname");
        $mail->Subject = "Test";
        $mail->MsgHTML("This is a test");
        $mail->addAddress("[email protected]", "Recipient Name");
        $mail->send();
    } catch (phpmailerException $e) {
        dd($e);
    } catch (Exception $e) {
        dd($e);
    }
    die('success');

And of course, you need to do a composer update after adding the depency to composer.json

However, i would prefer the laravel built in SwiftMailer. http://laravel.com/docs/5.0/mail