Catching PHP mail() errors and showing reasonable user error message

后端 未结 4 639
Happy的楠姐
Happy的楠姐 2020-12-06 06:57

I\'m writing a fairly simple register php script that uses PHP\'s built in mail() function to email the user an activation link.

The problem is that I c

相关标签:
4条回答
  • 2020-12-06 07:09

    Best would be to use a library like Swift Mailer that throws exceptions that can be easily handled.

    0 讨论(0)
  • 2020-12-06 07:11

    Use the boolean result to detect an error:

    $success = @mail(...);
    

    Then you want to find out which internal error caused the problem, so use:

    $error = error_get_last();
    preg_match("/\d+/", $error["message"], $error);
    switch ($error[0]) {
        case 554:
            ...
        default:
            ...
    

    Note that this works with php 5.2 onward only.

    There is no way to verify delivery or see transport error mails with PHP. You would need a pop3 polling handler for that.

    0 讨论(0)
  • 2020-12-06 07:31

    You want to catch as much as you can before you send off the mail, sanitize your inputs to make sure it really is what you expect it to be

    You can use filter_var to check that the email address really is an address, check that integers falls within your allowed range, etc.

    Set the mail header from address to a place where you can check for failed deliveries:

    $headers = 'From: webmaster@example.com' . "\r\n";
    

    You can also check that mail performed as expected:

    if(mail($to,$subject,$message))
    

    And a final thing, you probably don't want to display warnings in a live environment, you can turn those off, either through the ini file or using ini_set.

    0 讨论(0)
  • 2020-12-06 07:33

    A trivial error which I suffered from, was simply a lack of 'sendmail' in my system. Eventually, I have installed exim4 and configured it - and then php's mail(...) worked fine.

    See also:

    • http://www.w3schools.com/php/php_ref_mail.asp (Requirements)
    • http://wiki.debian.org/GmailAndExim4
    0 讨论(0)
提交回复
热议问题