PHP mail() 函式
示例
傳送一封簡單的電子郵件
<?php
// 訊息
$msg = "第一行文字\n第二行文字";
// 如果行長於 70 個字元,請使用 wordwrap()
$msg = wordwrap($msg,70);
// 傳送電子郵件
mail("someone@example.com","My subject",$msg);
?>
定義和用法
mail() 函式允許您直接從指令碼傳送電子郵件。
語法
mail(to,subject,message,headers,parameters);
引數值
引數 | 描述 |
---|---|
to | 必需。指定電子郵件的接收者。 |
主題 | 必需。指定電子郵件的主題。注意:此引數不能包含任何換行符。 |
message | 必需。定義要傳送的訊息。每行應以 LF (\n) 分隔。行不應超過 70 個字元。 Windows 注意:如果訊息中的某一行開頭是一個句點,則可能會被刪除。要解決此問題,請將句點替換為雙句點。 |
headers | 可選。指定附加標頭,如 From、Cc 和 Bcc。附加標頭應以 CRLF (\r\n) 分隔。 注意:傳送電子郵件時,必須包含 From 標頭。這可以在此引數中設定,也可以在 php.ini 檔案中設定。 |
parameters | 可選。為 sendmail 程式(在 sendmail_path 配置設定中定義)指定一個附加引數。(例如,在使用帶 -f sendmail 選項的 sendmail 時,這可用於設定信封發件人地址)。 |
技術詳情
返回值 | 返回 *address* 引數的雜湊值,失敗則返回 FALSE。注意:請記住,即使電子郵件已被接受進行投遞,也**不**表示電子郵件已成功傳送和接收! |
---|---|
PHP 版本 | 4+ |
PHP 更新日誌 | PHP 7.2:headers 引數也接受陣列。 PHP 5.4:為 *headers* 引數添加了標頭注入保護。 PHP 4.2.3:(僅限 Windows) 支援所有自定義標頭(如 From、Cc、Bcc 和 Date),並且不區分大小寫。 PHP 4.2.3:*parameters* 引數在安全模式下被停用。 PHP 4.0.5:添加了 *parameters* 引數。 |
更多示例
傳送帶有額外標頭的電子郵件
<?php
$to = "somebody@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com" . "\r\n" .
"CC: somebodyelse@example.com";
mail($to,$subject,$txt,$headers);
?>
傳送 HTML 電子郵件
<?php
$to = "somebody@example.com, somebodyelse@example.com";
$subject = "HTML email";
$message = "
<html>
<head>
<title>HTML email</title>
</head>
<body>
<p>This email contains HTML Tags!</p>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
</table>
</body>
</html>
";
// 傳送 HTML 電子郵件時始終設定 content-type
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// 更多標頭
$headers .= 'From: <webmaster@example.com>' . "\r\n";
$headers .= 'Cc: myboss@example.com' . "\r\n";
mail($to,$subject,$message,$headers);
?>
❮ 完整的 PHP Mail 參考