」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Laravel 可郵寄教程

Laravel 可郵寄教程

發佈於2024-11-08
瀏覽:611

在 Laravel 中发送电子邮件需要三个组件之间的协作:Laravel 邮件程序、Laravel 可邮件类和 Mail 外观。这三者中的每一个都涉及发送电子邮件生命周期的不同方面。

Mailers 是连接电子邮件发送服务(如 AWS SES、Sendgrid、Mailgun 等)的驱动程序,应用程序可使用这些服务将电子邮件转发给收件人。

Laravel Mailable 是表示要发送的电子邮件模板的特殊类。它包含电子邮件的所有典型信息,如内容、“收件人”字段、附件等。

最后,邮件门面是请求通过邮件程序驱动程序实际发送可邮寄邮件的访问点。

我有机会详细探索这个系统,现在 Inspector 在高峰期每小时发送超过 6000 封电子邮件。

Laravel Mailable Tutorial

我希望我的经验可以帮助您更好地理解框架的这个组件,因为 Laravel Mailable 是任何现代应用程序的关键组件之一。

想要了解更多技术文章,您可以在 Linkedin 或 X 上关注我。

Laravel 邮件程序配置

Laravel 中邮件程序驱动程序的配置位于 config/mail.php 文件中。可以定义多个邮件程序,每个邮件程序都有一个名称和一个传输驱动程序。

'mailgun' => [
    'transport' => 'mailgun',
    // 'client' => [
    //     'timeout' => 5,
    // ]

Laravel 将尝试使用它们,以防主电子邮件服务出现故障。

创建可邮寄的课程

mailable 是一个 PHP 类,代表您的应用程序发送的电子邮件。您可以使用 Artisan make 命令创建一个新的可邮寄类。

php artisan make:mail OrderConfirmation

可邮寄的配置通过信封、内容和附件三个主要方法进行,它们分别处理定义标头、消息正文和任何附件。

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class OrderConfirmation extends Mailable
{
    use Queueable;
    use SerializesModels;

    public function __construct(public Order $order) {}

    /**
     * Configure the email message
     */
    public function envelope()
    {
        return new Envelope(
            from: new Address('[email protected]', 'E-commerce'),
            subject: 'Order Confirmation',
        );
    }

    /**
     * Generate the body
     */
    public function content()
    {
        return new Content(
            markdown: 'emails.orders.confirm',
        );
    }

    /**
     * Configure the email attachements
     */
    public function attachments()
    {
        $code = $this->order->code;

        return [
            Attachment::fromPath("/path/to/order-{$code}.pdf"),
        ];
    }
}

电子邮件内容的呈现显然委托给适当的 Blade 模板。在 Blade 视图中,可以使用 mailable 类中定义的公共属性(上例中的 $order )检索用于呈现电子邮件的数据。

Code: {{ $order->code }}
Address: {{ $order->address }}
...

发送 Laravel 邮件

电子邮件的实际发送是通过 Mail 外观及其 to 和 send 方法进行的。

class OrderController extends Controller
{
    public function ship(Order $order)
    {
        // do stuff with the order

        // Send the confirmation email
        Mail::to($order->user)->send(new OrderConfirmation($order));
    }
}

电子邮件收件人可以作为电子邮件地址字符串传递,也可以通过用户对象或具有名称和电子邮件属性的对象集合传递。

要发送的实际电子邮件由可邮寄对象表示,该对象接收必要的属性来呈现与内容关联的 Blade 模板。

邮件门面提供了各种可链接的方法,允许您更详细地定义发送配置,包括收件人(使用抄送和密件抄送方法)以及发送时间和方法(队列或稍后)。

如果您想学习如何创建自己的外观,您可以阅读下面的文章:

https://inspector.dev/how-to-extend-laravel-with-driver-based-services/

将 Laravel Mailable 排队

由于发送电子邮件需要使用外部服务(Mailer 驱动程序),因此操作可能很慢,会对用户体验产生负面影响。

Laravel 允许您对电子邮件进行排队以便后台发送。如果您对如何大规模使用 Laravel 队列系统的教程感兴趣,您可以阅读下面的文章:

https://inspector.dev/what-worked-for-me-using-laravel-queues-from-the-basics-to-horizo​​n/

要推迟在后台发送电子邮件,您有两个选择:ShouldQueue 接口,或 Mail 门面的队列方法。

如前面的代码片段所示,可邮寄类是在默认情况下附加一些特征(如 Queueable)生成的。

它允许以编程方式使用邮件外观上的队列方法,而无需触及您的实现:

Mail::to($user)->queue(new OrderConfirmation($order));

您也可以在 Mailable 类中声明 ShouldQueue 接口的实现:

use Illuminate\Contracts\Queue\ShouldQueue;

class OrderConfirmation extends Mailable implements ShouldQueue
{
    ...
}

如果您使用此接口,则即使您在邮件门面上调用标准发送方法,电子邮件的发送也始终会排队。

// If the mailable class implements ShouldQueue these methods has the same behaviour.
Mail::to($user)->send(new OrderConfirmation($order));
Mail::to($user)->queue(new OrderConfirmation($order));

在浏览器中渲染 Laravel Mailable 模板

当您实现与电子邮件消息相关的视图时,获得 Blade 视图将呈现的最终结果的视觉反馈确实很有帮助。您可以使用 Laravel 项目中的 paths/mailable.php 文件来做到这一点。

/*
 * Render email in the browser.
 *
 * Visit https://homestead.test/mailable
 */
Route::get('/', function () {
    return new \App\Domains\Organization\Mails\IngestionLimitMail(
        \App\Domains\Organization\Models\Organization::firstOrFail()
    );
});

您可以从路由返回一个有效的 Mailable 实例,Laravel 将在浏览器中渲染视图。就像开发一个普通的网页一样。

Laravel Mailable Tutorial

最后记得在
中限制该路由的可用性 路线服务提供商:

class RouteServiceProvider extends ServiceProvider
{
    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        if (app()->environment('local')) {
            $this->mapMailableRoutes();
        }
    }

    /**
     * Render mailables in the browser.
     *
     * @return void
     */
    protected function mapMailableRoutes()
    {
        Route::prefix('mailable')
            ->group(base_path('routes/mailable.php'));
    }
}

想要了解更多技术文章,您可以在 Linkedin 或 X 上关注我。

免费监控您的 Laravel 应用程序

Inspector是专门为软件开发人员设计的代码执行监控工具。您不需要在服务器级别安装任何东西,只需安装 Laravel 包 就可以开始了。

如果您正在寻找 HTTP 监控、数据库查询见解以及将警报和通知转发到您首选消息传递环境的功能,请免费尝试 Inspector。注册您的帐户。

或者在网站上了解更多信息:https://inspector.dev

Laravel Mailable Tutorial

版本聲明 本文轉載於:https://dev.to/inspector/laravel-mailable-tutorial-59o0?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3