Send Email using PHP

php mail function

In this article we present a sample source code to send email using the PHP programming language. The default mail() function of PHP has the following parameters and returns a boolean value to show whether the mail() function was successful or not. We use error_get_last() function to get the last occurred error in case the mail() function returned ‘false’ value. The parameters are:

  • string $to
  • string $subject
  • string $message
  • array OR string $additional_headers = []
  • string $additional_params = “”

Here $additional_headers and $additional_params are optional parameters.

We also use to throw the exception if the message is not sent successfully.  It allows you to distinguish and route the error messages to a specific class for handling. Exceptions can provide much more details about the error message, rather than simple true/false or 0/1 values.

Here is the PHP Source Code to send email and throw SocketException if mail is not sent.

function SendEmail($to, $subject, $message, $headers, $params = null) {
 if (!@mail($to, $subject, $message, $headers, $params)) {
  $error = error_get_last();
  $msg = 'Could not send email: ' . (isset($error['message']) ? $error['message'] : 'unknown');
  throw new SocketException($msg);
 }
}
Categories: PHP Source Code
M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post