Laravel Multitenancy - Failed to authenticate on SMTP server with username "apiKey" using 2 possible authenticators

Viewed 21

I have been struggling with this for a couple of days now and non of the answers provided don't seem to help.

I am using the package stancl/tenancy to manage my multi-tenant app. Each tenant can have their own email configuration which are stored in a database table.

I have setup an account on Sendgrid account and had the configuration set up correctly like so:

MAIL_DRIVER = 'SMTP'
MAIL_HOST = 'smtp.sendgrid.net'
MAIL_PORT = 587
MAIL_USERNAME = 'apikey'
MAIL_PASSWORD = myApiKey
MAIL_FROM_ADDRESS="myemail@domain.com"

When I send a test email like this, it seems to work fine.

This is how the test email is sent.

Mail::raw("Sample message sent from the backend route (test-mail)", function ($message){
    $message->to("mytestemail@gmail.com")->subject("Sample Email");
});

However, when I try to make the changes dynamically within a controller, I get the error herein: Send Mail Error Below is how I am dynamically setting the configuration:

Route::get("test-mail", function (){
Config::set("mail", [
    "driver"    =>  "smtp",
    "host"      =>  "smtp.sendgrid.net",
    "port"      =>  587,
    "username"  =>  "apiKey",
    "password"  =>  myApiKey,
    "from"      =>  [
        "name"      =>  "Some Name",
        "address"   =>  "somename@email.com"
    ]
]);
Mail::raw("Sample message sent from the backend route (test-mail)", function ($message){
    $message->to("myrecepient@gmail.com")->subject("Sample Email");
});

A solution could really be helpful.

1 Answers

In your original config you had:

MAIL_USERNAME = 'apikey'

Which is correct. In your dynamic config you have:

    "username"  =>  "apiKey",

Which has a capital "K" and is incorrect. Change that to "apikey" and it will work again.

Related