在 PHP 上使用 mail() 發送電郵,如果沒有正確設定 Return-Path, 發出的郵件會使用系統的主機名稱,例如 apache@hostname.server, 以下是程式碼:
1 2 3 4 5 6 7 8 9 10 11 |
<?php $from = "from@example.com"; $to = "to@example.com"; $header = "FROM: " . $from . "\r\n". "Reply-To: " . $from . "\r\n". "Return-Path: " . $from . "\r\n". "Message-ID: <" . time() . "." . $from . ">". mail($to, "email subject", "The email body", $header); ?> |
在收到的郵件會看到寄件者是 from@example.com, 但當按下回覆時,會使用系統的主機名稱,除了回覆地址名,也會有部郵 email server 拒收,會在 email server 的紀錄檔出現 “invalid sender MX”。
原因是郵件的 Return-Path 並沒有使用 PHP 的 Return-Path 設定,郵件的 source 可以看到:
Return-Path:
Delivered-To:
要解決只要在 mail() 函式加入多一個參數,用 sendmail 的 -f 參數設定 Return Path, 具體寫法如下:
1 2 3 4 5 6 7 8 9 10 |
<?php $from = "from@example.com"; $to = "to@example.com"; $header = "FROM: " . $from . "\r\n". "Reply-To: " . $from . "\r\n". "Message-ID: <" . time() . "." . $from . ">". mail($to, "email subject", "The email body", $header, "-f".$from); ?> |