In this post, we are going to learn how to send email in PHP. The PHP mail() function is used to send emails from the script. This function has three mandatory parameters and two optional parameters.
Syntax
mail(to, subject, message, header, parameters);
Parameters:
Parameter | Description |
to | This field is mandatory. Specifies the address of the |
subject | This field is required. You can specify the subject of the email here. |
message | The message parameter is also required. The message to be sent is specified here. |
headers | Headers is an optional parameter. This is used to add additional headers such as From, Cc, Bcc. |
parameters | This is also an optional parameter. This parameter can be used to pass additional parameters to the sendmail program. |
Things to remember
- The subject should not contain any newline characters.
- Each line in the message should be separated with a LF (\n) and the lines should not exceed 70 characters.
- For Windows only – If a line in the message starts with a full stop, it will be removed. Replace the full stop with a double dot to solve this problem.
- The headers (if specified) should be separated with a CRLF (\r\n).
- There must be a from header when sending an email. You can set it in the headers parameter.
Replacing a dot with double dots (For Windows).
<?php
$text = str_replace("\n.", "\n..", $text);
?>
Return values
The PHP mail function returns TRUE if the mail was sent, else it will return FALSE.
Example – sending a simple mail
<?php
$message = "This is the message";
$message = wordwrap($message, 70, "\r\n");//to be used if the line is longer than 70 characters.
if(mail('someone@example.com', 'My Subject', $message))
{
echo "Mail has been sent.";
}
else
{
echo "Mail not sent.";
}
?>
//If this method does not work, try adding headers as shown in the next example.
Example – sending an email with headers
<?php
$to = 'someone@example.com';
$subject = 'the subject';
$message = 'hello world';
$headers = "From: from@yoursite.com" . "\r\n" .
"CC: anyone@example.com";
"Reply-To: mymail@example.com" . "\r\n";
if(mail($to, $subject, $message, $headers))
{
echo "Mail sent.";
}
else
{
echo "Mail not sent.";
}
?>
Example – sending an HTML email
<?php
$to = "someone@example.com";
$subject = "An HTML email";
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>This is an HTML email body</p>
</body>
</html>';
$header = "From:from@yoursite.com \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
if(mail($to,$subject,$message,$header))
{
echo "Message sent successfully.";
}
else
{
echo "Message not sent.";
}
?>