傳送電子郵件 - 基礎知識更多詳細資訊和完整示例
典型的電子郵件有三個主要元件:
- 收件人(表示為電子郵件地址)
- 主題
- 訊息體
用 PHP 傳送郵件就像呼叫內建函式 mail()
一樣簡單。mail()
最多需要五個引數,但前三個是傳送電子郵件所需的全部內容(儘管常用的四個引數如下所示)。前三個引數是:
- 收件人的電子郵件地址(字串)
- 電子郵件的主題(字串)
- 電子郵件的正文(字串)(例如電子郵件的內容)
一個最小的例子類似於以下程式碼:
mail('recipient@example.com', 'Email Subject', 'This is the email message body');
上面的簡單示例適用於有限的情況,例如硬編碼內部系統的電子郵件警報。但是,通常將作為 mail()
引數傳遞的資料放在變數中,以使程式碼更清晰,更易於管理(例如,從表單提交動態構建電子郵件)。
此外,mail()
接受第四個引數,允許你隨電子郵件傳送其他郵件標題。這些標題可以讓你設定:
- 使用者將看到的
From
名稱和電子郵件地址 - 使用者響應將傳送到的
Reply-To
電子郵件地址 - 其他非標準標題如
X-Mailer
可以告訴收件人這封電子郵件是通過 PHP 傳送的
$to = 'recipient@example.com'; // Could also be $to = $_POST['recipient'];
$subject = 'Email Subject'; // Could also be $subject = $_POST['subject'];
$message = 'This is the email message body'; // Could also be $message = $_POST['message'];
$headers = implode("\r\n", [
'From: John Conde <webmaster@example.com>',
'Reply-To: webmaster@example.com',
'X-Mailer: PHP/' . PHP_VERSION
]);
可選的第五個引數可用於將其他標誌作為命令列選項傳遞給配置為在傳送郵件時使用的程式,如 sendmail_path
配置設定所定義。例如,當使用帶有 -f
sendmail 選項的 sendmail / postfix 時,這可用於設定信封發件人地址。
$fifth = '-fno-reply@example.com';
雖然使用 mail()
可能非常可靠,但絕不保證在呼叫 mail()
時會傳送電子郵件。要檢視傳送電子郵件時是否存在潛在錯誤,你應該從 mail()
獲取返回值。如果郵件成功接受傳送,將返回 TRUE
。否則,你將收到 FALSE
。
$result = mail($to, $subject, $message, $headers, $fifth);
注 :雖然 mail()
可能返回 TRUE
,但這並不意味著電子郵件被髮送或電子郵件將被接收者接收。它僅表示郵件已成功切換到系統的郵件系統。
如果你希望傳送 HTML 電子郵件,則無需執行更多工作。你需要:
- 新增
MIME-Version
標頭 - 新增
Content-Type
標頭 - 確保你的電子郵件內容是 HTML
$to = 'recipient@example.com';
$subject = 'Email Subject';
$message = '<html><body>This is the email message body</body></html>';
$headers = implode("\r\n", [
'From: John Conde <webmaster@example.com>',
'Reply-To: webmaster@example.com',
'MIME-Version: 1.0',
'Content-Type: text/html; charset=ISO-8859-1',
'X-Mailer: PHP/' . PHP_VERSION
]);
這是使用 PHP 的 mail()
函式的完整示例
<?php
// Debugging tools. Only turn these on in your development environment.
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");
// Special mail settings that can make mail less likely to be considered spam
// and offers logging in case of technical difficulties.
ini_set("mail.log", "/tmp/mail.log");
ini_set("mail.add_x_header", TRUE);
// The components of our email
$to = 'recipient@example.com';
$subject = 'Email Subject';
$message = 'This is the email message body';
$headers = implode("\r\n", [
'From: webmaster@example.com',
'Reply-To: webmaster@example.com',
'X-Mailer: PHP/' . PHP_VERSION
]);
// Send the email
$result = mail($to, $subject, $message, $headers);
// Check the results and react accordingly
if ($result) {
// Success! Redirect to a thank you page. Use the
// POST/REDIRECT/GET pattern to prevent form resubmissions
// when a user refreshes the page.
header('Location: http://example.com/path/to/thank-you.php', true, 303);
exit;
}
else {
// Your mail was not sent. Check your logs to see if
// the reason was reported there for you.
}
也可以看看
官方檔案
相關的 Stack Overflow 問題
替代郵寄者
電郵伺服器
相關話題