Класс Mailable
Класс Mailable является базовым классом для создания почтовых сообщений в Laravel. Он позволяет определять структуру письма, его содержимое, вложения и получателей. Для создания письма необходимо создать класс, наследующий Mailable, и реализовать в нём метод envelope для настройки темы письма и метод content для определения содержимого. Также доступны методы для добавления вложений и передачи данных в представление.
Синтаксис
<?php
use IlluminateMailMailablesEnvelope;
use IlluminateMailMailablesContent;
class MyMail extends Mailable
{
public function envelope(): Envelope
{
return new Envelope(
subject: 'Subject of the email',
);
}
public function content(): Content
{
return new Content(
view: 'emails.my_view',
with: ['data' => $this->data],
);
}
}
?>
Пример
Создадим класс письма для отправки приветственного сообщения пользователю:
<?php
namespace AppMail;
use IlluminateBusQueueable;
use IlluminateMailMailable;
use IlluminateMailMailablesEnvelope;
use IlluminateMailMailablesContent;
use IlluminateQueueSerializesModels;
class WelcomeMail extends Mailable
{
use Queueable, SerializesModels;
public $user;
public function __construct($user)
{
$this->user = $user;
}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Welcome to our site!',
);
}
public function content(): Content
{
return new Content(
view: 'emails.welcome',
with: ['userName' => $this->user->name],
);
}
}
?>
Теперь создадим Blade-представление для этого письма:
<html>
<body>
<h1>Hello, {{ $userName }}!</h1>
<p>Welcome to our site. We are glad to see you.</p>
</body>
</html>
Отправим письмо с помощью фасада Mail:
<?php
namespace AppHttpControllers;
use AppMailWelcomeMail;
use AppModelsUser;
use IlluminateSupportFacadesMail;
class UserController extends Controller
{
public function register()
{
$user = User::find(1);
Mail::to($user->email)->send(new WelcomeMail($user));
return "Email sent successfully!";
}
}
?>
Результат выполнения кода:
"Email sent successfully!"
Пример
Добавим в письмо вложение из хранилища:
<?php
namespace AppMail;
use IlluminateBusQueueable;
use IlluminateMailMailable;
use IlluminateMailMailablesEnvelope;
use IlluminateMailMailablesContent;
use IlluminateMailMailablesAttachment;
use IlluminateQueueSerializesModels;
class InvoiceMail extends Mailable
{
use Queueable, SerializesModels;
public $order;
public function __construct($order)
{
$this->order = $order;
}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Your order invoice',
);
}
public function content(): Content
{
return new Content(
view: 'emails.invoice',
with: ['orderData' => $this->order],
);
}
public function attachments(): array
{
return [
Attachment::fromPath(storage_path('app/public/invoices/invoice.pdf'))
->as('invoice.pdf')
->withMime('application/pdf'),
];
}
}
?>
Отправим письмо с вложением:
<?php
namespace AppHttpControllers;
use AppMailInvoiceMail;
use AppModelsOrder;
use IlluminateSupportFacadesMail;
class OrderController extends Controller
{
public function complete($orderId)
{
$order = Order::find($orderId);
Mail::to('user@example.com')->send(new InvoiceMail($order));
return "Invoice sent!";
}
}
?>
Результат выполнения кода:
"Invoice sent!"
Пример
Передадим данные в письмо с помощью метода with в классе Mailable:
<?php
namespace AppMail;
use IlluminateBusQueueable;
use IlluminateMailMailable;
use IlluminateMailMailablesEnvelope;
use IlluminateMailMailablesContent;
use IlluminateQueueSerializesModels;
class NotificationMail extends Mailable
{
use Queueable, SerializesModels;
public $notification;
public function __construct($notification)
{
$this->notification = $notification;
}
public function envelope(): Envelope
{
return new Envelope(
subject: $this->notification['subject'],
);
}
public function content(): Content
{
return new Content(
view: 'emails.notification',
with: [
'message' => $this->notification['message'],
'actionUrl' => $this->notification['url'],
],
);
}
}
?>
Отправим уведомление пользователю:
<?php
namespace AppHttpControllers;
use AppMailNotificationMail;
use AppModelsUser;
use IlluminateSupportFacadesMail;
class NotificationController extends Controller
{
public function sendNotification($userId)
{
$user = User::find($userId);
$notification = [
'subject' => 'New update available',
'message' => 'We have released a new version of our app.',
'url' => 'https://example.com/download',
];
Mail::to($user->email)->send(new NotificationMail($notification));
return "Notification sent!";
}
}
?>
Результат выполнения кода:
"Notification sent!"