skip to Main Content

I make a php page to send email. I will give this page to multiple users, but I have no control of the server they will use. And some of them should have no SMTP server. So I try to handle this error.

For example, on my own computer, if I deactivate my SMTP server, I receive a "PHP Warning: mail(): Failed to connect to mailserver at …" error message.

My code :

  try
  {
    $okmail=mail($to,$Subject,$texte,$headers);
  }
  catch (Exception $ex)
  {
    ...
  }

But this code doesn’t throw an exception, it only write the error message (like an "echo(…)" statement).
I use this code in a xmlhttprequest page and use an xml type response. But the original page receive the error message before the xml text :
PHP Warning: mail(): Failed to connect to mailserver at … n1Email not send

How can I handle this "no SMTP" error ?

Thanks!

2

Answers


  1. Chosen as BEST ANSWER

    Thanks for your answers, but nothing works :(

    I find a solution by cleaning the output buffer by using ob_start(null,0,PHP_OUTPUT_HANDLER_CLEANABLE) and ob_clean() just after the mail() function.

    I don't understand why the mail function writes an error into the output buffer


  2. If I understand the problem correctly, the following directive will hide the warnings.

    ini_set('display_errors', 0);
    

    Instead of "try/catch" you can use the following approach.

    set_error_handler("warningHandler", E_USER_WARNING);
    
    // Trigger some warning here for testing purposes only (this is just an example).
    trigger_error('This here is the message from some warning ...', E_USER_WARNING);
    
    // If you need DNS Resource Records associated with a hostname.
    // $result = dns_get_record($_SERVER['HTTP_HOST']);
    
    // Restores the previous error handler function.
    restore_error_handler();
    
    // This is your custom warning handler.
    function warningHandler($errno, $errstr) {
        // Do what you want here ...
        echo $errno, ' ::: ', $errstr;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search