Skip to content

Instantly share code, notes, and snippets.

@pintend
Created March 6, 2023 18:11
Show Gist options
  • Select an option

  • Save pintend/1bb7ac42b812eeec50313fbe6b53a717 to your computer and use it in GitHub Desktop.

Select an option

Save pintend/1bb7ac42b812eeec50313fbe6b53a717 to your computer and use it in GitHub Desktop.
Send a simple notification email using the power of laravel without the complexities of laravels notifications
<?php
namespace App\Mail;
use BadMethodCallException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Notifications\Messages\SimpleMessage;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Traits\ForwardsCalls;
/**
* Send a simple notification email using the power of laravel without the complexities of laravels notifications
*
* Problem: Sometimes you want to send a basic email either during testing
* or whatever and you dont want to make a Mailable
* Solution: This class is your generic Mailable that can easily send any message
*
* Usage:
* MailMessage::for(User::first())
* ->line('The introduction to the notification.')
* ->action('Notification Action', url('/'))
* ->line('Thank you for using our application!')
* ->send()
*
* @mixin SimpleMessage
*/
class MailMessage extends Mailable
{
use Queueable, SerializesModels, ForwardsCalls;
protected SimpleMessage $message;
public function __construct()
{
$this->message = new SimpleMessage;
}
public function envelope(): Envelope
{
return new Envelope(
subject: $this->subject ?? 'Mail Message',
);
}
public function content(): Content
{
return new Content(
markdown: 'notifications::email',
with: $this->message->toArray(),
);
}
public function attachments(): array
{
return [];
}
public static function for(Model|string|array $to, ?string $name = null): static
{
$to = $to instanceof Model ? $to->email : $to;
$name ??= $to instanceof Model ? $to->name : $name;
return static::new()->when($to)->to($to, $name);
}
public static function new(): static
{
return new static;
}
public function send($mailer = null)
{
return parent::send($mailer ?? app('mail.manager')->mailer());
}
public function __call($method, $parameters)
{
try {
$this->forwardCallTo($this->message, $method, $parameters);
return $this;
} catch (BadMethodCallException $e) {
return parent::__call($method, $parameters);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment