PHP mail()Functions


PHP Mail 参考手册Complete PHP Mail Reference Manual

Definition and Usage

The mail() function allows you to send emails directly from a script.

Returns TRUE if the email was successfully accepted for delivery, otherwise returns FALSE.

Syntax

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

Parameter Description
to Required. Specifies the recipient 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. Separate each line with LF (\n). Lines should not exceed 70 characters.

Windows Note:When PHP is directly connected to an SMTP server, if a period is found at the beginning of a line in the message, it will be removed. To fix this, replace a single period with two periods:
<?php
$txt = str_replace("n.", "n..", $txt);
?>

headers Optional. Specifies additional headers, such as From, Cc, and Bcc. Additional headers should be separated with CRLF (\r\n).

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

parameters Optional. Specifies additional parameters for the sendmail program (defined in the sendmail_path configuration setting). For example: when sendmail is used with the -f sendmail option, sendmail can be used to set the sender address.


Tips and Notes

Note:You should keep in mind that the email being accepted for delivery does not mean the email reached its intended destination.


Example 1

Send a simple email:

<?php
$txt = "First line of textnSecond line of text";

// Use wordwrap() if lines are longer than 70 characters
$txt = wordwrap($txt,70);

// Send email
mail("somebody@example.com","My subject",$txt);
?>


Example 2

Send an email with additional headers:

<?php
$to = "somebody@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com" . "rn" .
"CC: somebodyelse@example.com";

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


Example 3

Send an 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" . "rn";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "rn";

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

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


PHP Mail 参考手册Complete PHP Mail Reference Manual Other Extensions