Skip to content
Advertisement

Laravel 5 and PHPMailer

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!

Advertisement

Answer

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("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');

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

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement