I have the following method in laravel my controller:
use AppEventsContactFormSubmitted;
public function submitContactForm(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|max:255',
'subject' => 'required|string|max:255',
'message' => 'required|string',
]);
// Dispatch the event with the validated data
event(new ContactFormSubmitted(
$validatedData['name'],
$validatedData['email'],
$validatedData['subject'],
$validatedData['message']
));
return response()->json(['message' => 'Form submitted successfully'], 200);
}
My code in app/event/ContactFormSubmitted.php
<?php
namespace AppEvents;
use IlluminateBroadcastingChannel;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateBroadcastingPresenceChannel;
use IlluminateBroadcastingPrivateChannel;
use IlluminateContractsBroadcastingShouldBroadcast;
use IlluminateFoundationEventsDispatchable;
use IlluminateQueueSerializesModels;
class ContactFormSubmitted
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $name;
public $email;
public $subject;
public $message;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($name, $email, $subject, $message)
{
$this->name = $name;
$this->email = $email;
$this->subject = $subject;
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* @return IlluminateBroadcastingChannel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
my code in app/Listeners/SendContactFormEmail.php
<?php
namespace AppListeners;
use IlluminateContractsQueueShouldQueue;
use IlluminateQueueInteractsWithQueue;
use IlluminateSupportFacadesMail;
use AppEventsContactFormSubmitted;
use AppMailContactFormMail;
class SendContactFormEmail
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param object $event
* @return void
*/
public function handle(ContactFormSubmitted $event)
{
// Send the email
Mail::to(config('app.mail_receiver'))->send(new ContactFormMail($event->name, $event->email, $event->subject, $event->message));
}
}
my code in app/Mail/ContactFormMail.php
<?php
namespace AppMail;
use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateMailMailable;
use IlluminateMailMailablesContent;
use IlluminateMailMailablesEnvelope;
use IlluminateQueueSerializesModels;
class ContactFormMail extends Mailable
{
use Queueable, SerializesModels;
public $name;
public $email;
public $subject;
public $message;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($name, $email, $subject, $message)
{
$this->name = $name;
$this->email = $email;
$this->subject = $subject;
$this->message = $message;
}
/**
* Get the message envelope.
*
* @return IlluminateMailMailablesEnvelope
*/
public function envelope()
{
return new Envelope(
subject: 'Contact Form Mail: ' . $this->subject,
);
}
/**
* Get the message content definition.
*
* @return IlluminateMailMailablesContent
*/
public function content()
{
return new Content(
markdown: 'emails.contactfrommail',
);
}
/**
* Get the attachments for the message.
*
* @return array
*/
public function attachments()
{
return [];
}
}
My code in EventServiceProvider.php
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
ContactFormSubmitted::class => [
SendContactFormEmail::class,
],
];
With the above code I’m trying to send email to MAIL_RECEIVER
listed .env file.
When I send the post request the above code returns Form submitted successfully
response but no email is sent by the application when I check the inbox.
I’ve tried sending email directly using Mail class. I get the email.
I cannot figure out why the email is not being sent with event and listener method.
Any help will be appreciated.
2
Answers
For anyone looking for answer, I fixed the issue by the add following method:
in my controller:
It seems like your code is set up correctly for sending an email using events and listeners in Laravel. Since you mentioned that sending email directly using the
Mail
class works, it suggests that your email configuration is correct. However, if the email is not being sent when using events and listeners, there might be an issue with event dispatching or queue workers.Here are some troubleshooting steps to identify and fix the issue:
Queue Configuration: Ensure that you have set up a queue driver in your
.env
file, and your queue worker is running. To send emails asynchronously through events and listeners, you need a working queue setup.Example
.env
configuration:Run the queue worker using the
artisan
command:Check the Queue Database Table: If you’re using the database queue driver, check the
jobs
table in your database. Verify that there are queued jobs related to sending the email. If they are stuck, try running the queue worker with the--queue
option to specify the queue you’re using.Example:
Event Listener Registration: Ensure that the
SendContactFormEmail
event listener is registered correctly in theEventServiceProvider.php
file. You’ve already done this, but double-check for any typos.Event Firing: Verify that the
ContactFormSubmitted
event is being fired correctly when you callevent(new ContactFormSubmitted(...))
in your controller.Check Log Files: Laravel logs events and errors. Check your Laravel log files (typically located in the
storage/logs
directory) for any error messages related to the email sending process. Log messages there might provide insights into what’s going wrong.Queue Worker Logs: Check the logs of your queue worker for any errors or issues. Queue worker logs can also provide information about why jobs are not being processed.
Retry Failed Jobs: If you find failed jobs in the
jobs
table, you can retry them using thequeue:retry
Artisan command:Replace
job-id
with the ID of the failed job.Queue Monitor: Consider using a package like Laravel Horizon or Laravel Telescope to monitor your queues and see if there are any issues.
Verify Email Sending Logic: Double-check your
SendContactFormEmail
listener to ensure that it’s correctly sending emails. You can add logging statements or use Laravel’sLog
facade to log information during email sending.