Seize the opportunity to gain new skills and reshape your career!

Choose a free learning path and get valuable insights from first-rate courses

Code has been added to clipboard!

PHP mail()

Reading time 2 min
Published Aug 14, 2017
Updated Sep 27, 2019

PHP mail(): Main Tips

  • Using PHP mail() lets you send emails using a script and communicate with your website visitors.
  • It's a great way to use data forms.

Correct Syntax: Parameters Explained

To avoid cases of PHP mail not working, always make sure you use the correct syntax in your PHP mail scripts:

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

Seems rather simple, doesn't it? See how PHP mail() works in a short PHP mail script example below:

// The text
$text = "The first message";

// use wordwrap() if the lines are more than 70 characters
$text = wordwrap($text, 70);

//send the email
mail("[email protected]", "My subject", $text);

Now, let's break it down and talk about each parameter that is used in the formula above:

Parameter Description
to This parameter is needed to specify the recipient of the email.
subject This parameter is needed to name the subject and can't have any newline characters.
message This parameter is used to write the message inside the email. A single line must not use more than 70 characters and ought to be split using \n to avoid PHP mail not working.
headers This parameter is optional and used to add new PHP mail headers (CC, BCC, From, etc.). All PHP mail headers must be separated using \r\n to avoid PHP mail not working.
parameters This parameter is optional and allows you to specify more additional parameters.

Note: If you want to make PHP send mail, you must use the header From as it is required. It can be set with this parameter or by editing the php.ini file.

Usage: Code Example

Let's see one more PHP mail example to make sure we got it right. In this code, you can notice that more mail headers are added:

$to = "[email protected]";
$subject = "My subject";
$txt = "Test";
$headers = "From: [email protected]" . "\r\n" .
"CC: [email protected]";

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