Search code examples
phplaravelemailphpmailerswiftmailer

Laravel email configuration: what am I missing?


I can send emails via PHPMailer, but not via Laravel. I assume my Laravel configuration to be wrong.

I'm sending from my local development environment.

Laravel error

Failed to authenticate on SMTP server with username "name@example.com" using 2 possible authenticators

Laravel controller

// ...
Mail::to('anyone@whatever.com')->send(new AnyEmailTemplate());
// ...

Laravel config/mail.php

return [
  'driver' => env('MAIL_DRIVER', 'smtp'),
  'host' => env('MAIL_HOST', 'mail.anyprovider.com'),
  'port' => env('MAIL_PORT', 587),
  'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'name@example.com'),
        'name' => env('MAIL_FROM_NAME', 'example.com'),
  ],
  'encryption' => env('MAIL_ENCRYPTION', 'tls'),
  'username' => env('MAIL_USERNAME', 'name@example.com'),
  'password' => env('MAIL_PASSWORD', 'supersecretpassword'),
  'sendmail' => '/usr/sbin/sendmail -bs',
  'markdown' => [
    'theme' => 'default',
    'paths' => [
      resource_path('views/vendor/mail'),
    ],
  ],
]

Laravel .env

MAIL_DRIVER=smtp
MAIL_HOST=mail.anyprovider.com
MAIL_PORT=587
MAIL_USERNAME=name@example.com
MAIL_PASSWORD=supersecretpassword
MAIL_ENCRYPTION=tls

PHPMailer script (works)

$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'mail.anyprovider.com';
$mail->SMTPAuth = true;
$mail->Username = 'name@example.com';
$mail->Password = 'supersecretpassword';
$mail->SMTPAutoTLS = false;
$mail->Port = 587;
$mail->CharSet = 'UTF-8';
$mail->setFrom('name@example.com', 'example.com');
$mail->addAddress('anyone@whatever.com');
$mail->isHTML(true);
$mail->Subject = 'Any subject';
$body = "Any content";
$altBody = "Any alternative content";
$mail->Body = $body;
$mail->AltBody = $altBody;
$mail->send();

Any idea how to configure Laravel, based on the settings used with PHPMailer?

Thanks in advance!


Solution

  • According to your PHPMailer script you should empty the value of MAIL_ENCRYPTION.

    Remember that if you have an .env file, this overrides your config/mail.php file.

    In your case your .env file becomes:

    MAIL_DRIVER=smtp MAIL_HOST=mail.anyprovider.com 
    MAIL_PORT=587 
    MAIL_USERNAME=name@example.com 
    MAIL_PASSWORD=supersecretpassword 
    MAIL_ENCRYPTION=
    

    While your config/mail.php becomes:

    ...
    'encryption' => env('MAIL_ENCRYPTION', ''), 
    ...
    

    NOTE
    After edit the files you have to tell to laravel about these changes with:

    • Cleaning the cache
    • Executing the command php artisan dump-autoload