How to send file with Email in Laravel Nova?

Viewed 180

I am sending a Newsletter Email to multiple recipients in markdown but I can't seem to attach a file to the email. The sending is triggered through an action:

Resource:

public function fields(Request $request)
{
    return [
        ID::make(__('ID'), 'id')->sortable(),

        Date::make('Created', 'created_at'),

        Markdown::make('Message', 'content')->alwaysShow(),

        File::make('File')->disk('public')
    ];
}

public function actions(Request $request)
{
    return [
        Actions\NewsletterMail::make()->standalone()
    ];
}

Action triggers controller function send:

public function handle(ActionFields $fields, Collection $models)
{
    app(NewsletterMailController::class)->send();
}

Controller gets all recipients emails and sends mailable to them:

public function send()
{
    $emails = DB::select('select * from newsletter_recipients order by id desc');

    foreach ($emails as $email) {
        Mail::to($email)->send(new NewsletterMail());
    }
}

Mailable gets the current newsletter email and returns it as markdown:

public function build()
{
    $this->content = DB::select('select * from newsletter_mails order by id desc limit 1')[0]->content;

    return $this->markdown('emails.newsletter')->with('content', $this->content);
}

As you can see the resource has an file field. I can assign a file to it in the nova dashboard but when the emails are sent, it arrives without attachment.

Anything I can do?

1 Answers

You have to use attach function in order to send files as attachments to email.

You can try this instead

return $this->markdown('emails.newsletter')
->with('content', $this->content)
->attach(filePath, ['as' => fileName,'mime' => 'application/pdf']);

Filepath will be location where your file is stored, make sure that folder has read write access.

Above code will send file as an attachment in your emails.

Related