Skip to content

Mailpit - 測試 Email 服務

Published: at 12:00 AM

Mailpit - 測試 Email 服務

針對開發人員提供帶有 API 的電子郵件和 SMTP 服務,可以透過自架或是 Docker 建立。
並提供 Web 介面來查看與捕獲測試郵件。

該篇文章將介紹如何使用 Docker 快速建立 Mailpit 服務,並且以 Laravel 測試發送郵件。 Mailpit

本篇目標:

  • 使用 Docker 快速建立 Mailpit 服務
  • 使用 Laravel 測試發送郵件
    • 傳送純文字郵件
    • 發送 template 的信件

目的:

通常測試發送郵件時,會使用 Mailtrap 這類的服務,但是這些服務都是需要註冊帳號,並且有使用次數限制,因此透過 Mailpit 可以快速建立自己的測試郵件服務。

使用 Docker 快速建立 Mailpit 服務

透過 Docker 快速在本機建立該服務,目前有的 Docker Registry :

docker run -d --restart unless-stopped --name=mailpit -p 8025:8025 -p 1025:1025 axllent/mailpit

透過上述指令,你將會在本機建立起 Mailpit 服務,預設

使用 Laravel 測試發送郵件

設定 .env 檔案,設定郵件服務

MAIL_MAILER=smtp
MAIL_HOST=127.0.0.1
MAIL_PORT=1025
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=

使用 Artisan Tinker 指令測試

透過 Laravel Facade Mail 來發送郵件。

傳送純文字郵件

使用箭頭函數 PHP7.4後才支援 簡化程式碼:(快速測試服務是否可正常使用)

Mail::raw('Hello world', fn ($message) => $message->to('[email protected]')->from('[email protected]'));

不使用箭頭函數程式碼:

use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Mail;

Mail::raw('Hello world', function (Message $message) {
    $message->to('[email protected]')->from('[email protected]');
});
  • to: 收件者
  • from: 寄件者
  • raw: 郵件內容

發送 template 的信件

若是要發送動態內容郵件和使用基本的樣板傳送,可以使用 plain 方法,並且傳遞 blade 檔案。 使用箭頭函數 PHP7.4後才支援 簡化程式碼:

use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Mail;

Mail::plain('welcome', [], fn (Message $message) => $message->to('[email protected]')->subject('Hello')->from('notification@localhost'));

不使用箭頭函數程式碼,這邊使用命名參數(PHP8後才支援):

use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Mail;

Mail::plain(
    view: 'welcome', // welcome.blade.php
    data: [], // 傳遞的資料
    callback: function (Message $message) { // Message 實例
        $message->to('[email protected]')
            ->subject('Hello')
            ->from('notification@localhost');
    }
);

參考資料:


Previous Post
RabbitMQ(1)
Next Post
Kubernetes學習筆記(3.5) Harbor