PHP mail() 函數(shù)
定義和用法
mail() 函數(shù)允許您從腳本中直接發(fā)送電子郵件。
如果郵件的投遞被成功地接收,則返回 true,否則返回 false。
語法
mail(to,subject,message,headers,parameters)
參數(shù) | 描述 |
---|---|
to | 必需。規(guī)定郵件的接收者。 |
subject | 必需。規(guī)定郵件的主題。該參數(shù)不能包含任何換行字符。 |
message | 必需。規(guī)定要發(fā)送的消息。 |
headers | 必需。規(guī)定額外的報頭,比如 From, Cc 以及 Bcc。 |
parameters | 必需。規(guī)定 sendmail 程序的額外參數(shù)。 |
說明
在 message 參數(shù)規(guī)定的消息中,行之間必須以一個 LF(\n)分隔。每行不能超過 70 個字符。
(Windows 下)當 PHP 直接連接到 SMTP 服務器時,如果在一行開頭發(fā)現(xiàn)一個句號,則會被刪掉。要避免此問題,將單個句號替換成兩個句號。
<?php $text = str_replace("\n.", "\n..", $text); ?>
提示和注釋
注釋:您需要緊記,郵件投遞被接受,并不意味著郵件到達了計劃的目的地。
例子
例子 1
發(fā)送一封簡單的郵件:
<?php
$txt = "First line of text\nSecond line of text";
// 如果一行大于 70 個字符,請使用 wordwrap()。
$txt = wordwrap($txt,70);
// 發(fā)送郵件
mail("somebody@example.com","My subject",$txt);
?>
例子 2
發(fā)送帶有額外報頭的 email:
<?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);
?>
例子 3
發(fā)送一封 HTML email:
<?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>
";
// 當發(fā)送 HTML 電子郵件時,請始終設置 content-type
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
// 更多報頭
$headers .= 'From: <webmaster@example.com>' . "\r\n";
$headers .= 'Cc: myboss@example.com' . "\r\n";
mail($to,$subject,$message,$headers);
?>