PHP mail() 函数
定义和用法
mail() 函数允许您从脚本中直接发送电子邮件。
如果邮件的投递被成功地接收,则返回 true,否则返回 false。
语法
mail(to,subject,message,headers,parameters)
参数 | 描述 |
---|---|
to | 必需。规定邮件的接收者。 |
subject | 必需。规定邮件的主题。该参数不能包含任何换行字符。 |
message | 必需。规定要发送的消息。 |
headers | 必需。规定额外的报头,比如 From, Cc 以及 Bcc。 |
parameters | 必需。规定 sendmail 程序的额外参数。 |
说明
在 message 参数规定的消息中,行之间必须以一个 LF(\n)分隔。每行不能超过 70 个字符。
(Windows 下)当 PHP 直接连接到 SMTP 服务器时,如果在一行开头发现一个句号,则会被删掉。要避免此问题,将单个句号替换成两个句号。
<?php $text = str_replace("\n.", "\n..", $text); ?>
Petunjuk dan Komentar
Komentar:Anda perlu ingat, penerimaan pengiriman email tidak bermakna email telah sampai ke tujuan yang dijadwalkan.
Contoh
Contoh 1
Hantar email yang sederhana:
<?php $txt = "First line of text\nSecond line of text"; // Jika baris melebihi 70 aksara, gunakan wordwrap(). $txt = wordwrap($txt,70); // Hantar email mail("somebody@example.com","My subject",$txt); ?>
Contoh 2
Hantar email dengan header tambahan:
<?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); ?>
Contoh 3
Hantar email HTML:
<?php $to = "somebody@example.com, somebodyelse@example.com"; $subject = "Email HTML"; $message = " <html> <head> <title>Email HTML</title> </head> <body> <p>Email ini mengandungi Tag HTML!</p> <table> <tr> <th>Nama Depan</th> <th>>Nama Belakang</th> </tr> <tr> <td>Bill</td> <td>Gates</td> </tr> </table> </body> </html> "; // Semakkan content-type selalu ketika menghantar email HTML $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n"; // Lebih banyak header $headers .= 'From: <webmaster@example.com>' . "\r\n"; $headers .= 'Cc: myboss@example.com' . "\r\n"; mail($to,$subject,$message,$headers); ?>