PHP Mail

by Vincy. Last modified on July 2nd, 2022.

PHP provides a mail() function for sending simple mail using PHP scripts. For that, the 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)

The first three arguments are obvious and more clear about their purpose. a Header and Additional Parameters are needed to set values like From Address to avoid errors while sending a mail.

This From Address is by default set with the php.ini file. But in some rare cases of having a 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 a set of other email-related settings like smtp, smtp_port, sendmail_path and etc.

Example: PHP mail()

The following PHP program is for sending simple mail using the PHP mail function. It starts with the initialization of the mail() function’s five parameters discussed above. For additional headers, CC and BCC are specified with email addresses for which a 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 the boolean value TRUE if the mail is accepted for delivery and print a success message to the browser. Otherwise, it returns false with a 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 an efficient method to send email using the PHP program. Because we can not transfer bulk data using this function.

And also, it has poor performance in sending emails to more than one recipient and is not secure enough. To send an email to each recipient, the PHP mail() function attempts to open the SMTP socket every time which leads to poor performance.

To get rid of such inconvenience with this function, we can better go with other alternative email packages, for example, the PEAR::Mail package.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page