psudo
psudo

Reputation: 1558

Sending mail from event and listener in laravel 9

I have the following method in laravel my controller:

    use App\Events\ContactFormSubmitted;
    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 App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

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 \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

my code in app/Listeners/SendContactFormEmail.php

<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Mail;
use App\Events\ContactFormSubmitted;
use App\Mail\ContactFormMail;

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 App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

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 \Illuminate\Mail\Mailables\Envelope
     */
    public function envelope()
    {
        return new Envelope(
            subject: 'Contact Form Mail: ' . $this->subject,
        );
    }

    /**
     * Get the message content definition.
     *
     * @return \Illuminate\Mail\Mailables\Content
     */
    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.

Upvotes: 0

Views: 850

Answers (1)

psudo
psudo

Reputation: 1558

For anyone looking for answer, I fixed the issue by the add following method:

in my controller:

use App\Events\ContactFormSubmitted;
use Event;


    public function submitContactForm(Request $request)
    {
     //validation code goes here

        Event::dispatch(
            new ContactFormSubmitted(
                $validatedData['name'],
                $validatedData['email'],
                $validatedData['subject'],
                $validatedData['message']
            )
        );
        return response()->json(['message' => 'Email sent succesfully'], 200);
    }

Upvotes: 0

Related Questions