🚨 Get Your Free NFT Certificate Mint by Completing the Web3 Exam! START NOW

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.
DataCamp
Pros
  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion
Udemy
Pros
  • Easy to navigate
  • No technical issues
  • Seems to care about its users
Main Features
  • Huge variety of courses
  • 30-day refund policy
  • Free certificates of completion

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:

Example
<?php
// 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:

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

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