mailhog 輕量級的 SMTP 測試發送

mailhog工具是輕量級的 SMTP 測試服務,它們可以捕獲所有發送的郵件,並允許你在瀏覽器中查看這些郵件。它們非常適合在開發環境中使用,而不需要發送實際郵件。

Mac安裝

$ brew install mailhog

啟動

$ mailhog

Windows安裝

前往github https://github.com/mailhog/MailHog/releases

在「Assets」部分,找到對應的 Windows 版本(通常是 .exe 文件,例如 MailHog_windows_amd64.exe)。

Mailhog 將在 http://localhost:8025 提供一個網頁界面來查看抓到的送出郵件。

在主機上的發信端設定是

SMTP Host: 127.0.0.1
SMTP Port: 1025

使用 laravel的情境是編輯 ./evn

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

使用wordpress情境下使用像 WP Mail SMTP 這樣的外掛可以讓你輕鬆設置郵件配置:

SMTP Host: 127.0.0.1
SMTP Port: 1025
Encryption: None

使用phpmailer的情境,使用 PHP 的 mail() 函數或 PHPMailer,則需要在設定 SMTP 發送。

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();
    $mail->Host = '127.0.0.1';  // Mailhog SMTP Service
    $mail->Port = 1025;         // Mailhog SMTP Port
    $mail->SMTPAuth = false;    // 不需要驗證
    $mail->SMTPSecure = false;  // 不使用加密

    // 收件人、發件人等
    $mail->setFrom('[email protected]', 'Mailer');
    $mail->addAddress('[email protected]', 'Recipient Name');

    // 內容
    $mail->isHTML(true);
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

後續註記:

在收到的郵件內中,如果看不出內容,可以試試看用base64_decode後再看看