mail()

创建于 2024-12-03 / 53
字体: [默认] [大] [更大]

❮ PHP Mail 参考手册

实例

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

<?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() 函数允许您从脚本中直接发送电子邮件。

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

语法

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

参数值

参数 描述
to 必需。规定邮件的接收者。
subject 必需。规定邮件的主题。注释: 该参数不能包含任何换行字符。
message 必需。定义要发送的消息。 每行应该用 LF (\n) 分隔。 行不应超过 70 个字符。

Windows 注释:如果在消息的行首发现句号,则它可能会被删除。 要解决此问题,请将句号替换为双点:
<?php
$txt = str_replace("\n.", "\n..", $txt);
?>

headers 可选。指定附加标头,例如 From、Cc 和 Bcc。 附加标头应使用 CRLF (\r\n) 分隔。

注释: 发送电子邮件时,它必须包含 From 标头。 这可以用这个参数或在 php.ini 文件中设置。

parameters 可选。指定 sendmail 程序的附加参数(在 sendmail_path 配置设置中定义的参数)。 (即,当使用带有 -f sendmail 选项的 sendmail 时,这可用于设置信封发件人地址)

说明

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

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


提示和注释

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


技术细节

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

更多实例

发送带有额外报头的 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);
?>

发送一封 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>
";

// 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);
?>
❮ Complete PHP Mail Reference
0 人点赞过