'How can i send a laravel email with SMTP without getting the .env data?
I need to fetch the SMTP data in the account of user that will be saved in the database. That way it couldn't pull the data from the .env file.
I'm using Laravel 8
For example, instead of looking for SMTP authentication in .env I would look in the database:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mail;
use Config;
use App\Mail\EmailManager;
class NewsletterController extends Controller
{
public function testEmail(Request $request){
$array['view'] = 'emails.newsletter';
$array['subject'] = "SMTP Test";
$array['from'] = '[email protected]';
$array['content'] = "This is a test email.";
Config::set('mail.host', 'smtp.mailtrap.io');
Config::set('mail.username', '[email protected]');
Config::set('mail.password', 'd13ea2a29a5cee');
Config::set('mail.port', 587);
try {
Mail::to($request->email)->send(new EmailManager($array));
} catch (\Exception $e) {
dd($e);
}
flash(translate('An email has been sent.'))->success();
return back();
}
}
I solved.
I Created a file with configutations:
/app/Providers/MailConfigServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
use App\Models\EmailSetting;
use Config;
class MailConfigServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
if (\Schema::hasTable('email_settings')) {
$mail = DB::table('email_settings')->first();
if ($mail) //checking if table is not empty
{
$config = array(
'driver' => $mail->driver,
'host' => $mail->host,
'port' => $mail->port,
'from' => $mail->from,
'encryption' => $mail->encryption,
'username' => $mail->username,
'password' => $mail->password,
'sendmail' => '/usr/sbin/sendmail -bs',
'pretend' => false,
);
Config::set('mail', $config);
}
}
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
}
}
And added this line on app/config
App\Providers\MailConfigServiceProvider::class
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|