Mostly, we do a static email configuration in any programming/scripting language. The static configuration will work only for one user. So, what if you want to do an email setup for multiple users. In other words, if you are creating a kind of a portal or CRM in which you require to allow users to set their email configuration. So, is it possible to configure an email setting for every individual user? Yes, it is. In that case, you can store the configuration values in the database. Then, as per the current user, it can be accessed from the database and set the configuration. When we will do the dynamic email configuration in Laravel, we will be overriding the email configuration by providing the necessary details through the database.
As we know, in Laravel, we configure the email settings in the .env file. It has linked with the mail.php file available in the config directory. Today, in this post, I will be showing you the step by step guide for overriding the default email configuration and make it dynamic. So, let’s go by creating a new project for this post.
Prerequisites
For creating this Laravel 8 project setup, you will require to have the following configurations.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
Create Laravel 8 Project For Dynamic Email Configuration
For creating a new project in Laravel 8, I will be using the composer dependency manager. So, hit the below command to create the project.
composer create-project --prefer-dist laravel/laravel EmailConfiguration
The above command will start installing the Laravel in the specified directory. Here, the Laravel 8 installation has started.
After creating this project setup, let’s create and configure the database.
Laravel 8 Client Side Form Validation Using jQuery
Create and Configure Database For Laravel 8 Project
For managing the database, we will be using the MySQL. So, create a database first.
CREATE DATABASE email_configuration;
After creating the database, we need to connect it with our application. So, for connecting the database in Laravel, you will have to navigate to the .env file of the project. Then add the database credentials as showing below.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=email_configuration
DB_USERNAME=root
DB_PASSWORD=root
Before creating the email configuration, I will be installing the User Auth using the Jetstream package. So, that we can manage the authentication for the logged user.
Create RESTful APIs in Laravel 8 Using Passport Auth
Install Jetstream Package For Auth in Laravel 8
We will have to install the Jetstream package for auth. This will take a couple of minutes to install the Jetstream.
composer require laravel/jetstream
Hence, after installing the Jetstream package, we will have to install the Livewire.
php artisan jetstream:install livewire
The above command will install the livewire package inside the Jetstream.
Therefore, after installing the livewire package, we will have to run the npm install command. So, the node modules will be installed.
npm install && npm run dev
The above command will install the node modules.
You can check the installation of packages is successful or not. So, open the composer.json file and check the installed package.
After installing the Jetstream and Livewire package, you will have to do the migration. Actually, after the package installation, the migrations files for the user authentication has been added. So, in order to check the authentication, you will have to migrate the tables first. But, we will require another model and migration. So, lets create it first.
How to Upload Image in CKEditor 5 Using Laravel 8
Create Model and Migration
For creating the email configuration dynamically, you will require a table to store the email settings. Hence, you will have to create a model, migration and the controller for this. So, you can do all in a single line of command.
php artisan make:model EmailConfiguration -mc
After creating the model, migration and controller file, you will have to add the fields for storing the email configuration in the table.
Add Migration For Email Configuration
Open the database/migrations folder. Then open the email_configurations migration file and add the below fields.
public function up()
{
Schema::create('email_configurations', function (Blueprint $table) {
$table->id();
$table->bigInteger('user_id')->nullable();
$table->string('driver')->nullable();
$table->string('host')->nullable();
$table->string('port')->nullable();
$table->string('encryption')->nullable();
$table->string('user_name')->nullable();
$table->string('password')->nullable();
$table->string('sender_name')->nullable();
$table->string('sender_email')->nullable();
$table->timestamps();
});
}
In the next step, you will have to set the fillable data for the model.
Add Fillable Data For Dynamic Email Configuration
Open the model EmailConfiguration.php file and add the below fillable data there.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class EmailConfiguration extends Model
{
use HasFactory;
protected $fillable = [
"user_id",
"driver",
"host",
"port",
"encryption",
"user_name" ,
"password",
"sender_name",
"sender_email"
];
}
At last, we have to migrate the migration files. Here, all the tables will be migrated into the database.
php artisan migrate
In the database, we have the following tables after the migration.
Now, you can check the login and register for the authentication.
How to Create and Use Database Seeder in Laravel 8
Check Login and Register in JetStream
Run the application to check the result. Here, we can see, we have the user register and login option. Hence, we can proceed with the dynamic email configuration of the currently logged user. So, firstly, do a signup and enter into the dashboard.
Here, after the successful sign up, I have redirected to the Dashboard page. It will look like this.
Here, in the dashboard, I will do some modifications to the default layout for creating the Email configuration. Also, I will create a view for sending emails.
How to Use Guzzle Http in Laravel 8 For Request Handling
Create Dynamic Email Configuration in Laravel 8
Firstly, I will change the dashboard layout and then will create a form for creating the email configuration.
Hence, navigate to the resources/views/dashboard.blade.php. Now, put the below snippet there.
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Dashboard') }}
</h2>
</x-slot>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden sm:rounded-lg">
<div class="min-h-screen flex justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
<div class="max-w-md w-full space-y-8">
@if(Session::has("success"))
<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative" role="alert">
<strong class="font-bold">Success!</strong>
<span class="block sm:inline">{{Session::get('success')}}</span>
<span class="absolute top-0 bottom-0 right-0 px-4 py-3">
<svg class="fill-current h-6 w-6 text-green-500" role="button" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><title>Close</title><path d="M14.348 14.849a1.2 1.2 0 0 1-1.697 0L10 11.819l-2.651 3.029a1.2 1.2 0 1 1-1.697-1.697l2.758-3.15-2.759-3.152a1.2 1.2 0 1 1 1.697-1.697L10 8.183l2.651-3.031a1.2 1.2 0 1 1 1.697 1.697l-2.758 3.152 2.758 3.15a1.2 1.2 0 0 1 0 1.698z"/></svg>
</span>
</div>
@elseif(Session::has("failed"))
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
<strong class="font-bold">Failed!</strong>
<span class="block sm:inline">{{Session::get('failed')}}</span>
<span class="absolute top-0 bottom-0 right-0 px-4 py-3">
<svg class="fill-current h-6 w-6 text-red-500" role="button" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><title>Close</title><path d="M14.348 14.849a1.2 1.2 0 0 1-1.697 0L10 11.819l-2.651 3.029a1.2 1.2 0 1 1-1.697-1.697l2.758-3.15-2.759-3.152a1.2 1.2 0 1 1 1.697-1.697L10 8.183l2.651-3.031a1.2 1.2 0 1 1 1.697 1.697l-2.758 3.152 2.758 3.15a1.2 1.2 0 0 1 0 1.698z"/></svg>
</span>
</div>
@endif
<div>
<h2 class="text-center text-3xl font-extrabold text-gray-900">Create Email Configuration</h2>
</div>
<form class="mt-8 space-y-6" action="{{route('configuration.store')}}" method="POST">
@csrf
<div class="shadow-sm -space-y-px mb-4">
<div>
<label for="driver" class="sr-only">SMTP Driver</label>
<input id="driver" name="driver" type="text" required class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Driver">
</div>
</div>
<div class="shadow-sm -space-y-px mb-4">
<div>
<label for="host-name" class="sr-only">Host Name</label>
<input id="host-name" name="hostName" type="text" required class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Host">
</div>
</div>
<div class="shadow-sm -space-y-px mb-4">
<div>
<label for="port" class="sr-only">Port</label>
<input id="port" name="port" type="text" required class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Port">
</div>
</div>
<div class="shadow-sm -space-y-px mb-4">
<div>
<label for="userName" class="sr-only">User Name</label>
<input id="userName" name="userName" type="text" required class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="User Name">
</div>
</div>
<div class="shadow-sm -space-y-px mb-4">
<div>
<label for="password" class="sr-only">Password</label>
<input id="password" name="password" type="password" autocomplete="current-password" required class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Password">
</div>
</div>
<div class="shadow-sm -space-y-px mb-4">
<div>
<label for="senderName" class="sr-only">Sender Name</label>
<input id="senderName" name="senderName" type="text" required class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Sender Name">
</div>
</div>
<div class="shadow-sm -space-y-px mb-4">
<div>
<label for="senderEmail" class="sr-only">Sender Email</label>
<input id="senderEmail" name="senderEmail" type="text" required class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Sender Email">
</div>
</div>
<div>
<button type="submit" class="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">Save</button>
</form>
</div>
</div>
</div>
</div>
</div>
</x-app-layout>
In the dashboard area, I have added the above form snippet. The above snippet will generate the below form. Here, I have used the Tailwind CSS for styling the form design instead of Bootstrap.
In the next step, we will store the value from the above form. So, add the below snippet in the EmailConfigurationController.
// =========== [ Create email configuration ] ==========
public function createConfiguration(Request $request) {
$configuration = EmailConfiguration::create([
"user_id" => Auth::user()->id,
"driver" => $request->driver,
"host" => $request->hostName,
"port" => $request->port,
"encryption" => $request->encryption,
"user_name" => $request->userName,
"password" => $request->password,
"sender_name" => $request->senderName,
"sender_email" => $request->senderEmail
]);
if(!is_null($configuration)) {
return back()->with("success", "Email configuration created.");
}
else {
return back()->with("failed", "Email configuration not created.");
}
}
Then add a route respectively for the above function. So, you will have to add the route in the web.php file.
<?php
use App\Http\Controllers\EmailConfigurationController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view("welcome");
});
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::post("configuration", [EmailConfigurationController::class, "createConfiguration"])->name("configuration.store");
Now, run the application to store the email configuration. Here, I have entered the SMTP details as showing below.
After filling up the correct SMTP details just save it. In the response, you will get the success message as showing below.
So, here, you have the email configuration in the database. Now, in the next step, you will require a provider class from where you can set the configuration setting dynamically.
How to Send Emails Using Twilio Sendgrid in Laravel 8
Create a Service Provider Class in Laravel 8
You can create a service provider in Laravel for overriding any configuration setting. Here, we will do the dynamic email configuration using the service provider class.
Firstly, create a provider class using the below command.
php artisan make:provider MailConfigProvider
After creating the provider class, just open it. You will find the file inside the app/Providers. There will be two methods in this file. The register() and the boot() method. Here, we will do the database synchronization that means we will fetching the value for email configuration from the database. Hence, we will have to write the business logic inside the boot() method.
So, simply add the below code in your file.
<?php
namespace App\Providers;
use App\Models\EmailConfiguration;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
class MailConfigProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot() {
// get email view data in provider class
view()->composer('email', function ($view) {
if(isset(Auth::user()->id)) {
$configuration = EmailConfiguration::where("user_id", Auth::user()->id)->first();
if(!is_null($configuration)) {
$config = array(
'driver' => $configuration->driver,
'host' => $configuration->host,
'port' => $configuration->port,
'username' => $configuration->user_name,
'password' => $configuration->password,
'encryption' => $configuration->encryption,
'from' => array('address' => $configuration->sender_email, 'name' => $configuration->sender_name),
);
Config::set('mail', $config);
}
}
});
}
}
Before moving to the next step, let me explain what I did in the above snippet.
In the boot() method, firstly, I have got the current logged user using the auth::user(). But, we cannot directly get the Session value in the Service provider class. As per the Laravel lifecycle, the service provider class loads before the session. So, here, I retrieved the session (auth user) from the specific view. That means, when the view will load, we will get the auth user from that view. So, here I have set the view name email. So, that when the compose email view will be opened, it will fetch the auth user.
In the next step, the service provider class will need to register.
Register Provider Class
To register the provider class, navigate to the config/app.php. Then under the providers array, you will need to add the class.
'providers' => [
....
....
....
App\Providers\MailConfigProvider::class,
]
In the next step, I will add one more menu item in the dashboard. Then on that menu item, we will add a basic form for sending email.
Add Menu in JetStream Dashboard Layout
In the next step, I will add one more menu in the dashboard section. Currently, you can see there is only one menu that is Dashboard. So, here, I want to add one more menu. So, for adding the menus, you will have to navigate the views folder. Inside the views folder, you will see navigation-dropdown.blade.php file. So, open it, and add one more menu/tab like this.
{{-- add menu for sending email --}}
<div class="hidden space-x-8 sm:-my-px sm:ml-10 sm:flex">
<x-jet-nav-link href="{{ route('email') }}" :active="request()->routeIs('email')">
{{ __('Send Email') }}
</x-jet-nav-link>
</div>
Here, I have added the above menu in the top bar section of the dashboard area. Also, I have added a route for this in the web.php file.
Route::get("email", [EmailConfigurationController::class, "composeEmail"])->name("email");
Now, refresh the page to see the new changes.
Next, we will another basic form for sending an email to the recipient. This will confirm that the dynamic email configuration is working or not.
For the above route handling, I have created a method in the same controller. Here, I returned the view that we will create in the next step.
// ============ [ email configuration view ] ===========
public function composeEmail() {
return view("email");
}
Now, we will create a view.
Create a View For Sending Email
Now, for the above route, we will require a view to load. So, here, you will have to create a basic form. Hence,open the resources folder and create a view for loading the compose email form with the name email.blade.php. Now, add the below snippet there.
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Email') }}
</h2>
</x-slot>
<div class="py-6">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden sm:rounded-lg">
<div class="min-h-screen flex justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
<div class="max-w-md w-full space-y-8">
@if(Session::has("success"))
<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative" role="alert">
<strong class="font-bold">Success!</strong>
<span class="block sm:inline">{{Session::get('success')}}</span>
<span class="absolute top-0 bottom-0 right-0 px-4 py-3">
<svg class="fill-current h-6 w-6 text-green-500" role="button" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><title>Close</title><path d="M14.348 14.849a1.2 1.2 0 0 1-1.697 0L10 11.819l-2.651 3.029a1.2 1.2 0 1 1-1.697-1.697l2.758-3.15-2.759-3.152a1.2 1.2 0 1 1 1.697-1.697L10 8.183l2.651-3.031a1.2 1.2 0 1 1 1.697 1.697l-2.758 3.152 2.758 3.15a1.2 1.2 0 0 1 0 1.698z"/></svg>
</span>
</div>
@elseif(Session::has("failed"))
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
<strong class="font-bold">Failed!</strong>
<span class="block sm:inline">{{Session::get('failed')}}</span>
<span class="absolute top-0 bottom-0 right-0 px-4 py-3">
<svg class="fill-current h-6 w-6 text-red-500" role="button" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><title>Close</title><path d="M14.348 14.849a1.2 1.2 0 0 1-1.697 0L10 11.819l-2.651 3.029a1.2 1.2 0 1 1-1.697-1.697l2.758-3.15-2.759-3.152a1.2 1.2 0 1 1 1.697-1.697L10 8.183l2.651-3.031a1.2 1.2 0 1 1 1.697 1.697l-2.758 3.152 2.758 3.15a1.2 1.2 0 0 1 0 1.698z"/></svg>
</span>
</div>
@endif
<div>
<h2 class="text-center text-3xl font-extrabold text-gray-900">Send Email </h2>
</div>
<form class="mt-8 space-y-6" action="{{route('compose-email')}}" method="POST">
@csrf
<div class="shadow-sm -space-y-px mb-4">
<div>
<label for="emailAddress" class="sr-only">Email Address</label>
<input id="emailAddress" name="emailAddress" type="email" required class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Email Address">
</div>
</div>
<div class="shadow-sm -space-y-px mb-4">
<div>
<label for="message" class="sr-only">Message</label>
<textarea id="message" name="message" type="text" required class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Message"></textarea>
</div>
</div>
<button type="submit" class="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">Compose Email</button>
</form>
</div>
</div>
</div>
</div>
</div>
</x-app-layout>
Run the application to see the new changes. Here, you can see, we have a basic form for sending email to the recipient.
In the next step, you will have to create a mail class for sending email in Laravel.
Create a Mail Class in Laravel 8
For sending email, you will require a mail class in Laravel. So, you can create a mail class using the artisan command.
php artisan make:mail DynamicEmail
The above command will create a Mail class inside the app/Mail folder. Now, add the below snippet there.
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class DynamicEmail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('email-template')->with("data", $this->data);
}
}
We can attach an email template for the message. So, create another view for email template.
Create a View For Email Template in Laravel 8
Here, I will add a basic email template to pass the email message dynamically. Hence, just place the below code.
<!DOCTYPE html>
<html>
<head>
<title> Email Template in Laravel </title>
</head>
<body>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden sm:rounded-lg">
<div class="min-h-screen flex justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
<div class="max-w-md w-full space-y-8">
{{$data['message']}}
</div>
</div>
</div>
</div>
</div>
</body>
</html>
For sending email we will have to read the form to the controller. Therefore, you will require to add one more snippet in the EmailConfigurationController.
public function sendEmail(Request $request) {
$toEmail = $request->emailAddress;
$data = array(
"message" => $request->message
);
// pass dynamic message to mail class
Mail::to($toEmail)->send(new DynamicEmail($data));
if(Mail::failures() != 0) {
return back()->with("success", "E-mail sent successfully!");
}
else {
return back()->with("failed", "E-mail not sent!");
}
}
At last, you will need to add one more route (POST) route for composing the email.
Add POST Route For Sending Email
Go back to the web.php file, now, add the below POST route inside it.
Route::post("compose-email", [EmailConfigurationController::class, "sendEmail"]);
Now, run the application to see whether the dynamic email configuration is working for sending email or not.
I have added the email recipient and message in the email body. After that, I clicked on the Compose Email button.
In the response, I got the success message. It seems email sent successfully through the dynamic email configuration.
Let’s check the mailbox for the confirmation.
Here, I have got the email. That means everything worked absolutely fine without any issue.
Conclusion
Finally, we have achieved the dynamic email configuration by storing the value in the database. We set the configuration value in the service provider at boot time of the application. So, by following this approach, every user can set their own email configuration for a single application. So, I hope, this tutorial will help you to create at a big level of the application like any CRM or Portal where the email configuration always requires. If you get any error in the entire steps then don’t hesitate to put your comment. I will definitely help you.
Tensa says
Hi, I did follow all the instructions but it is not working.
How it will fetch email config dynamic? Do i need to re-write the .env file or do i need to configure mail.php?
Please help
Umesh Rana says
Here, the email configuration is not getting through .env file. Instead of that, I created a service provider (MailConfigProvider) and through that service provider, I have overridden the email setting. So, here, the email is sending through this dynamic email config, not from the .env file.
Also, you haven’t mentioned what error you are getting?
Ellis says
I also followed everything but it’s not working. The sender’s email address is the one setup in .ENV instead from the database.
Umesh Rana says
Firstly, make sure, you are able to store sender details in the database. If the values are stored, then you can fetch them from the database and set them to the service provider instead of the existing .env file. If possible then show your code, I will go through it.
eriko says
“Umesh Rana” skipped service registration
config/app.php
To register your provider, add it to the array:
‘providers’ => [
// Other Service Providers
App\Providers\MailConfigProvider::class,
],
Umesh Rana says
Thank you for your observation. I skipped that step but now added it.
Gabrielle says
Hi, I am trying to allow admins to edit email templates on the frontend before sending them. Any idea how to achieve this? Thanks in advance.
Umesh Rana says
Do you want to change the email template (HTML) or its content like you want to pass data dynamically in the email template?
Jorge Bustamante says
Hello, thank you very much for your article it is great, but I have a question, in case I had an api and did not use the views as you think this configuration should do: That its mail configuration is applied for users with authorization, while Unauthorized users have the default configuration configured in the environment file, as I indicate again the problem occurs to me when I use laravel as an api.
Umesh Rana says
Hi Jorge,
If you are using token-based API then you can check the authorized user and call the API in the boot() method of the service provider. That should work for fetching the data from the database on the basis of the authorized user. In my case, I have used view, hence, I fetched the logged user data from view. Actually, according to the Laravel life cycle, session() and cookie() are loading after the service provider class registered. So, you cannot retrieve any value from the session and cookie in the service provider class.
tosin says
Connection could not be established with host mailhog :stream_socket_client(): php_network_getaddresses: getaddrinfo failed: No such host is known.
Umesh Rana says
Your host is not configured properly. Which mail host you are using?
Do one thing try to check that mail configuration through the .env file and check if it is working.
tosin says
I could see var_dump() the values from DB but when I send tot the route sendEmail it does not work. I think The configuration is overwritten once you go to another view
Nodar Salim says
How can I make this work with queue.
When I add Implements ShouldQueue fails .
is there any work around ?
Thanks for the post
Asfahan says
i am get this error
Cannot send message without a sender address
terki says
hello thank for this article, very good.
i have just a problem , when i send a email with the link menu “send Email” i have
“The POST method is not supported for this route. Supported methods: GET, HEAD.”
thank for any solution
Umesh Rana says
You haven’t defined the POST route for sending email. Please check the web.php file inside the routes folder.
developer says
i have just a problem , when i send a email with the link menu “send Email” i have
“The POST method is not supported for this route. Supported methods: GET, HEAD.”
thank for any solution
developer says
The GET method is not supported for this route. Supported methods: POST.
Umesh Rana says
Did you add the POST route for sending emails? If not then add re-check the code or you may add the below route in the web.php file.
Route::post("compose-email", [EmailConfigurationController::class, "sendEmail"]);
Ren says
Great, works, but doesn’t override .env settings. Email comes through from host/address in .env
Umesh Rana says
Try to remove email configuration settings from .env file and call it dynamically through providers.
Rohit says
can you help me to explain which things we should remove like smtp , host, port or something else , please explain , thank you.
Sana says
I got this error –
Argument 1 passed to Illuminate\Mail\MailManager::getConfig() must be of the type string, null given
please give me the solution, i have followed your article.
Umesh Rana says
It seems there is some issue with the configuration. Please make sure, you are passing all the required parameters.
Sana says
I follow all this step but this is not overwrite .env file. please give me solution. thank you.
Umesh Rana says
What error you are getting?
Sana says
Connection not established host mailhost not connected
Umesh Rana says
The mail configuration is not working properly so it is unable to send the email.
For the debugging purpose, you can follow these steps-
1. Either you can test using .env configuration static.
2. Secondly, you can pass same configuration in the ServiceProvider whatever you created and check if it will work.
Sana says
I have already check these step. My smtp details are correct. When I put it on .env file it send email correctly. But when I removed SMTP details from .env file and use service provider it give me error. I have used same SMTP details.
Umesh Rana says
If possible, you can share your code through Git and share it on my email (refer to contact us) so that I will be able to debug it.