PHP Mail

PHP provides mail() function for sending simple mail using PHP scripts. For that, mail() function requires three arguments compulsorily and also two optional arguments, so totally five possible arguments as shown below.

  • Recipient Email Address (Mandatory).
  • Email Subject (Mandatory)
  • Email Context or Message Body (Mandatory)
  • Additional Header Information (Optional)
  • Additional Parameters (Optional)

php_mail

First three arguments are obvious and more clear about their purpose. Rather Additional Header and Additional Parameters are needed to set values like From Address to avoid error while sending email. This From Address is by default set with php.ini file. But in some rare cases of having custom php.ini file and no value is set for From Address, at that time Additional Parameters of this mail() function is used. And then, Additional Header argument that includes more header information like CC, BCC and etc.

Note: Not only FromAddress as sendmail_from, php.ini also holds set of other mail related settings like smtp, smtp_port, sendmail_path and etc.

Example: PHP mail()

The following PHP program is for sending simple mail using PHP mail function. It starts with the initialization of mail() function’s five parameters discussed above. For additional headers, CC and BCC are specified with email addresses for which copy of this email content will be sent. And, finally From Address is set as an additional parameter.

All the arguments are used for the PHP mail() function in the following program. This function will return boolean value TRUE, if the mail is accepted for delivery and print success message to the browser . Otherwise, it returns false with failure notice.

<?php
$recipientEmail = "Enter Recipient Email Here!";
$emailSubject = "PHP Mailing Function";
$emailContext = "Sending content using PHP mail function";

$emailHeaders = "Cc: Replace email address" . "\r\n";
$emailHeaders .= "Bcc: Replace email address" . "\r\n";

$fromAddress = "-fpostmaster@localhost";
$emailStatus = mail($recipientEmail, $emailSubject, $emailContext, $emailHeaders, $fromAddress);
if($emailStatus) {
echo "EMail Sent Successfully!";
} else {
echo "No Email is sent";
}
?>

But this mail() function is not efficient method to send email using PHP program. Because, we can not transfer bulk data using this function. And also, it has poor performance on sending email to more than one recipient and not secure enough. To send email for each recipient, PHP mail() function attempts to open the SMTP socket every time which leads poor performance. To get rid of such inconvenience with this function, we can better go with other alternative email packages, for example PEAR::Mail package.

This PHP code tutorial was published on June 4, 2013.

↑ Back to Top