PHP mail() function

Definition and usage

The mail() function allows you to send email directly from the script.

If the delivery of the email is successfully received, it returns true; otherwise, it returns false.

Syntax

mail(to,subject,message,headers,parameters)
Parameters Description
to Required. Specifies the recipient of the email.
subject Required. Specifies the subject of the email. This parameter cannot contain any newline characters.
message Required. Specifies the message to be sent.
headers Required. Specifies additional headers, such as From, Cc, and Bcc.
parameters Required. Specifies additional parameters for the sendmail program.

Description

In message In the message specified by the parameters, lines must be separated by a LF (\n). Each line must not exceed 70 characters.

(On Windows) When PHP connects directly to the SMTP server, if a period is found at the beginning of a line, it will be deleted. To avoid this issue, replace a single period with two periods.

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

Tips and comments

Note:Remember that the acceptance of email delivery does not necessarily mean that the email has reached its intended destination.

Example

Example 1

Send a simple email:

<?php
$txt = "First line of text\nSecond line of text";
// If a line is greater than 70 characters, use wordwrap().
$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" . "\r\n" .
"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>Bill</td>
<td>Gates</td>
</tr>
</table>
</body>
</html>
";
// Set content-type always when sending HTML email
$headers = 'MIME-Version: 1.0' . '\r\n';
$headers .= 'Content-type:text/html;charset=iso-8859-1' . '\r\n';
// More headers
$headers .= 'From: <webmaster@example.com>' . '\r\n';
$headers .= 'Cc: myboss@example.com' . '\r\n';
mail($to, $subject, $message, $headers);
?>