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.