Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 839
Sas Sam Avatar asked Apr 07 '15 07:04

Sas Sam


1 Answers

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

like image 130
shock_gone_wild Avatar answered Oct 09 '22 06:10

shock_gone_wild