PHP mail() 函数

定义和用法

mail() 函数允许您从脚本中直接发送电子邮件。

如果邮件的投递被成功地接收,则返回 true,否则返回 false。

语法
  1. mail(to,subject,message,headers,parameters)
参数描述
to必需。规定邮件的接收者。
subject必需。规定邮件的主题。该参数不能包含任何换行字符。
message必需。规定要发送的消息。
headers必需。规定额外的报头,比如 From, Cc 以及 Bcc。
parameters必需。规定 sendmail 程序的额外参数。
说明

在 message 参数规定的消息中,行之间必须以一个 LF(\n)分隔。每行不能超过 70 个字符。

(Windows 下)当 PHP 直接连接到 SMTP 服务器时,如果在一行开头发现一个句号,则会被删掉。要避免此问题,将单个句号替换成两个句号。

  1. <?php
  2. $text = str_replace("\n.", "\n..", $text);
  3. ?>

提示和注释

注释:您需要紧记,邮件投递被接受,并不意味着邮件到达了计划的目的地。


例子

例子 1

发送一封简单的邮件:

  1. <?php
  2. $txt = "First line of text\nSecond line of text";
  3. // 如果一行大于 70 个字符,请使用 wordwrap()。
  4. $txt = wordwrap($txt,70);
  5. // 发送邮件
  6. mail("somebody@example.com","My subject",$txt);
  7. ?>
例子 2

发送带有额外报头的 email:

  1. <?php
  2. $to = "somebody@example.com";
  3. $subject = "My subject";
  4. $txt = "Hello world!";
  5. $headers = "From: webmaster@example.com" . "\r\n" .
  6. "CC: somebodyelse@example.com";
  7. mail($to,$subject,$txt,$headers);
  8. ?>
例子 3

发送一封 HTML email:

  1. <?php
  2. $to = "somebody@example.com, somebodyelse@example.com";
  3. $subject = "HTML email";
  4. $message = "
  5. <html>
  6. <head>
  7. <title>HTML email</title>
  8. </head>
  9. <body>
  10. <p>This email contains HTML Tags!</p>
  11. <table>
  12. <tr>
  13. <th>Firstname</th>
  14. <th>Lastname</th>
  15. </tr>
  16. <tr>
  17. <td>John</td>
  18. <td>Doe</td>
  19. </tr>
  20. </table>
  21. </body>
  22. </html>
  23. ";
  24. // 当发送 HTML 电子邮件时,请始终设置 content-type
  25. $headers = "MIME-Version: 1.0" . "\r\n";
  26. $headers .= "Content-type:text/html;charset=utf-8" . "\r\n";
  27. // 更多报头
  28. $headers .= 'From: <webmaster@example.com>' . "\r\n";
  29. $headers .= 'Cc: myboss@example.com' . "\r\n";
  30. mail($to,$subject,$message,$headers);
  31. ?>

分类导航