目录

PHP mail() 函数

❮ PHP 邮件参考

示例

发送一封简单的电子邮件:

<?php
// the message
$msg = "First line of text\nSecond line of text";

// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);

// send email
mail("someone@example.com","My subject",$msg);
?>

定义和用法

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

语法

mail( to,subject,message,headers,parameters);

参数值

Parameter Description
to Required. Specifies the receiver / receivers of the email
subject Required. Specifies the subject of the email. Note: This parameter cannot contain any newline characters
message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters.

Windows note: If a full stop is found on the beginning of a line in the message, it might be removed. To solve this problem, replace the full stop with a double dot:
<?php
$txt = str_replace("\n.", "\n..", $txt);
?>

headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n).

Note: When sending an email, it must contain a From header. This can be set with this parameter or in the php.ini file.

parameters Optional. Specifies an additional parameter to the sendmail program (the one defined in the sendmail_path configuration setting). (i.e. this can be used to set the envelope sender address when using sendmail with the -f sendmail option)


技术细节

返回值: 返回的哈希值地址参数,如果失败则为 FALSE。笔记:请记住,即使电子邮件被接受发送,并不意味着电子邮件实际上已发送和接收!
PHP 版本: 4+
PHP 变更日志: PHP 7.2: headers 参数也接受数组
PHP 5.4:添加了标头注入保护标头范围。
PHP 4.3.0:(仅限 Windows)支持所有自定义标头(例如 From、Cc、Bcc 和 Date),并且不区分大小写。
PHP 4.2.3:范围安全模式下参数被禁用
PHP 4.0.5:范围添加了参数

更多示例

发送带有额外标头的电子邮件:

<?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>
";

// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
$headers .= 'From: <webmaster@example.com>' . "\r\n";
$headers .= 'Cc: myboss@example.com' . "\r\n";

mail($to,$subject,$message,$headers);
?>

❮ 完整的 PHP 邮件参考