Как узнать ошибку mail php

Try this. If I got any error on any file then I got error mail on my email id. Create two files index.php and checkErrorEmail.php and uploaded them to your server. Then load index.php with your browser.

Index.php

<?php
    include('checkErrorEmail.php');
    include('dereporting.php');
    $temp;
    echo 'hi '.$temp;
?>

checkErrorEmail.php

<?php
  // Destinations
  define("ADMIN_EMAIL", "pradeep.callus7@hotmail.com");
  //define("LOG_FILE", "/my/home/errors.log");

  // Destination types
  define("DEST_EMAIL", "1");
  //define("DEST_LOGFILE", "3");

  /* Examples */

  // Send an e-mail to the administrator
  //error_log("Fix me!", DEST_EMAIL, ADMIN_EMAIL);

  // Write the error to our log file
  //error_log("Error", DEST_LOGFILE, LOG_FILE);

  /**
    * my_error_handler($errno, $errstr, $errfile, $errline)
    *
    * Author(s): thanosb, ddonahue
    * Date: May 11, 2008
    * 
    * custom error handler
    *
    * Parameters:
    *  $errno:   Error level
    *  $errstr:  Error message
    *  $errfile: File in which the error was raised
    *  $errline: Line at which the error occurred
    */

  function my_error_handler($errno, $errstr, $errfile, $errline)
  {  
  echo "<br><br><br><br>errno ".$errno.",<br>errstr ".$errstr.",<br>errfile ".$errfile.",<br>errline ".$errline;
      if($errno)
      {
              error_log("Error: $errstr n error on line $errline in file $errfile n", DEST_EMAIL, ADMIN_EMAIL);
      }
    /*switch ($errno) {
      case E_USER_ERROR:
        // Send an e-mail to the administrator
        error_log("Error: $errstr n Fatal error on line $errline in file $errfile n", DEST_EMAIL, ADMIN_EMAIL);

        // Write the error to our log file
        //error_log("Error: $errstr n Fatal error on line $errline in file $errfile n", DEST_LOGFILE, LOG_FILE);
        break;

      case E_USER_WARNING:
        // Write the error to our log file
        //error_log("Warning: $errstr n in $errfile on line $errline n", DEST_LOGFILE, LOG_FILE);
        break;

      case E_USER_NOTICE:
        // Write the error to our log file
       // error_log("Notice: $errstr n in $errfile on line $errline n", DEST_LOGFILE, LOG_FILE);
        break;

      default:
        // Write the error to our log file
        //error_log("Unknown error [#$errno]: $errstr n in $errfile on line $errline n", DEST_LOGFILE, LOG_FILE);
        break;
    }*/

    // Don't execute PHP's internal error handler
    return TRUE;
  }


  // Use set_error_handler() to tell PHP to use our method
  $old_error_handler = set_error_handler("my_error_handler");


?>

I am sending mails from php mail() : and I want to receive a failed message if sending is failed to the destinatio .

$to = 'itsdfdsf@7sisters.in';
    $email_from = "info@7sisters.in";

    $full_name = 'XXXX';
    $from_mail = $full_name.'<'.$email_from.'>';



    $subject = "testing sender name";
    $message = "";
    $message .= '
            <p><strong>This is only a test mail. Please do not reply.</strong><br />
    ';
    $from = $from_mail;

    //$headers = "" .
    //         "Reply-To:" . $from . "rn" .
    //         "X-Mailer: PHP/" . phpversion();

    $headers = "From:" . $from_mail . "rn" .
               "Reply-To:" . $from_mail . "rn" .
               "X-Mailer: PHP/" . phpversion();


    $headers .= 'MIME-Version: 1.0' . "rn";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";        

    if(!mail($to,$subject,$message,$headers))
    {
        echo 'failed !!';
    }

But although $to mail does no exist,it is not showing failed !!

asked Dec 5, 2011 at 11:52

AssamGuy's user avatar

4

The mail method is just sending the mail out. If it does not receive any errors (e.g. by not finding the server etc), it will return succesfull. You will not be able to know if the mail actually landed in the inbox of the recipient unless you create some code around bounced emails etc.

answered Dec 5, 2011 at 11:57

Bas Slagter's user avatar

Bas SlagterBas Slagter

9,8117 gold badges47 silver badges78 bronze badges

I think what you want is to check for a real email not only a valid formatted email. So I would suggest you to have a look at this blog

Martin.'s user avatar

Martin.

10.5k3 gold badges42 silver badges68 bronze badges

answered Dec 5, 2011 at 11:59

SERPRO's user avatar

SERPROSERPRO

10k8 gold badges46 silver badges63 bronze badges

0

check the return from of mail

Returns TRUE if the mail was successfully accepted for delivery, FALSE
otherwise.

It is important to note that just because the mail was accepted for
delivery, it does NOT mean the mail will actually reach the intended
destination.

Although the fact it is returning true probably means that your mail program is accepting the message but then failing when it tries to send to no one…

You should run the $to through a validator to check its a valid address and then throw an error if its not, don’t rely on mail() to filter out things which you already know are wrong, or can check against easily.

—UPDATE

Then check out @SeRPRo , but what your trying to do is hard work to test programatically — its far easier and more reliable to send an e-mail which requires the user to click a link to verify that it’s real than try querying SMTP servers which all have different behaviour (read: are broken to different degrees). Also note that your intended behaviour (code wise) is hard to differentiate from a spammers so don’t be surprised to find it difficult going if you avoid the verification e-mail route.

answered Dec 5, 2011 at 11:57

James Butler's user avatar

James ButlerJames Butler

3,8541 gold badge26 silver badges38 bronze badges

1

But although $to mail does no exist,it is not showing failed !!

actually the fact that mail is being delivered to SMTP server, doesn’t mean it will be delivered to the end user. There’s no easy way in PHP to check whether it’s delivered.

answered Dec 5, 2011 at 11:55

Martin.'s user avatar

Martin.Martin.

10.5k3 gold badges42 silver badges68 bronze badges

You could CC yourself as a way of testing that it is leaving the outbox.

answered Dec 5, 2011 at 11:59

abcde123483's user avatar

abcde123483abcde123483

3,8754 gold badges41 silver badges41 bronze badges

1

In my case it helped to set the return-path via the commandline parameter «-f», which can be passed in the $additional_parameters parameter of mail(). so i call

mail($to, $subject, $message, $headers, "-f address.where.i.want.the.bounces@xy.com");

… according to some comments on http://www.php.net/manual/en/function.mail.php hosting-inviroments react different and have different restrictions (address might need to be registered in the same hosting-account, or be on the same domain, the same as the «From:» in the heade … and so on)

The page where I got the bounces to be received (with non of the mentioned restrictions, as it seems) is hosted at Domainfactory http://www.df.eu

answered May 23, 2012 at 14:06

johjoh's user avatar

johjohjohjoh

4644 silver badges18 bronze badges

Use phpmailer to send email and set $mail->AddCustomHeader(‘Return-path:bounce@mail.com’);
This will send bounce email at bounce@mail.com if recipient mail id does not exist or recipient does not receive email by any other case.

answered Apr 2, 2013 at 5:24

Chese

Guest


  • #1

Отловить в PHP ошибку при отправлении почты(mail)

Функция mail возврашает TRUE или FALSE, а можно ли при FALSE отловить, почему именно не ушло письмо т.е. код ошибки.

  • #2

используй [m]imap_mail[/m]
тексты ошибок — через [m]imap_errors[/m], [m]imap_last_error[/m]

Chese

Guest


  • #3

А если нет imap, его в самом деле нет :)

  • #4

тогда все пропало.
в исходниках нет возврата ошибок — есть либо TRUE, либо FALSE

Код:

        if (php_mail(to, subject, message, headers, extra_cmd TSRMLS_CC)) {
                RETVAL_TRUE;
        } else {
                RETVAL_FALSE;
        }

Chese

Guest


  • #5

Понято, значит будем просто ругаться без объяснения причин.

  • #6

Автор оригинала: Chese
Понято, значит будем просто ругаться без объяснения причин.

Что кстати не корректно:) Но другого выхода нет…

Barlone

Guest


  • #7

Re: Отловить в PHP ошибку при отправлении почты(mail)

Автор оригинала: Chese
Функция mail возврашает TRUE или FALSE, а можно ли при FALSE отловить, почему именно не ушло письмо т.е. код ошибки.

Не уйти оно может только по одной причине — в php.ini путь к sendmail указан неправильно.

Chese

Guest


  • #8

Не уйти оно может только по одной причине — в php.ini путь к sendmail указан неправильно

Ну по чему? ;) Если емайл верный, а записи в DNS про домен нет, или у Sendmail переполнена очередь и он не возьмет в отправку….

Barlone

Guest


  • #9

Если емайл верный, а записи в DNS про домен нет

… то письмо успешно передастся sendmail’у, а вот он уже не сможет его доставить. Очередь переполнена? Ну не знаю, тестировать не возьмусь :)

trolik

Guest


  • #10

зачем юзать функцию mail?
передавай парметры sendmail и пиши тело письма с заголовками ему же… а потом анализируй код возврата

-ViT-

Guest


  • #11

А вот что сегодня выдал броузер….

Автор оригинала: tony2001
тогда все пропало.
в исходниках нет возврата ошибок — есть либо TRUE, либо FALSE

Я как раз сегодня добрался до функции mail. Иногда пропадает переменная сессии и в качестве e-mail передается пустое поле — и тогда броузер пишет (цитирую):

Warning: Bad Message destination in F:WEBProjectsinetpubwwwrootPHPDevelopingRegform2.phtml on line 73

То есть какая-то же диагностика есть?? :confused:

Barlone

Guest


  • #12

Под виндой mail работает совсем не так, как под unix.

  • #13

ViT:
какая диагностика ?
неправильный аргумент приходит — вот и ошибка.
проверяй ДО и все будет ок.
исходники посмотри — там все достаточно ясно.

-ViT-

Guest


  • #14

2 tony2001: — это я знаю, и в данном случае потерянный аргумент — это нормально, это стадия отладки у меня шла… Я просто хочу спросить (абсолютно ПО теме топика) — что раз пришло такое сообщение, значит все же что-то как-то диагносцируется? В исходниках (приведенных тобой) — все совершенно ясно, простейшая конструкция.. Но кто тогда вернул мне этот мессадж? :)

2 Barlone: ты прав, это PHP у меня крутится под IIS, и клиент, с которого снято сообщение — WinXP/Opera. Но ведь ядро PHP (сорцы) — одинаково или тоже нет?

  • #15

речь шла о том «как определить почему не доставляется письмо».
так ?
логично предположить, что элементарная проверка на «а что нам передали как е-мэйл?» там присутствует.
так ?
вот ты видишь ее результат.
более подробно — смотри исходники.

честно говоря, немного не понимаю понятия «диагностика».
если проверка аргумента — это диагностика, то да, диагностика есть.

Barlone

Guest


  • #16

Специально посмотрел в исходники РНР :)
Для Win (#ifdef PHP_WIN32) там идет отправка по smtp, и какие-то ошибки в smtp-сессии видимо отлавливаются.
Для не-win никаких проверок не делается, popen’ом открывается sendmail, ему пихаются «To:», «Subject:», остальные заголовки (как есть) и тело письма. Ошибка может быть только одна: «Could not execute mail delivery program» если popen не сработал.

-ViT-

Guest


  • #17

2 Barlone:
Вот спасибо, а то я никак до исходников не доберусь! :(
Лично мне так механизм стал намного понятнее!
Следовательно, если переносить хост на Unix-сервера, то надо вновь очень тщательно тестить/вычищать/модернизировать все скрипты…. мда, жаль :(

  • #18

http://cvs.php.net/co.php/php4/ext/standard/mail.c?login=2&r=1.66.2.1
смотреть
php_mail() & PHP_FUNCTION(mail)

Barlone

Guest


  • #19

Ну тестить-то надо в любом случае. :) Модернизировать ? Зачем ? Если письмо формируется правильно, без разницы, как оно отправляется.
Кстати, если указать sendmail_path под виндой, то он будет использоваться, и отправляться как на unix. Остается только найти sendmail под винду. :)

Chese

Guest


  • #20

Автор оригинала: trolik
зачем юзать функцию mail?
передавай парметры sendmail и пиши тело письма с заголовками ему же… а потом анализируй код возврата

Молчит как партизан sendmail

PHP:

error_reporting(E_ALL);
$mailer = popen ("/usr/sbin/sendmail -t -i","w");
fwrite ($mailer,"Subject: Test
From: [email][email protected][/email]
To: [email protected]@aaa.com

Test!!!
");
$read = fread($mailer, 2096);
echo $read;
pclose ($mailer);

PiCoderman

php

  • PHP

  • Электронная почта

Как узнать ошибку Mail() ? Просто возвращает все время FALSE, а в чем дело не знаю(


  • Вопрос задан

    более трёх лет назад

  • 2892 просмотра


Комментировать

Пригласить эксперта


Ответы на вопрос 2

0neS

  • PiCoderman

    Там ничего нету. И cPanel в сервисе проверки отправлений ничего нету

alexdb

Проверьте настройки php.ini
sendmail_from
sendmail_path

Подробно

  • PiCoderman

    У меня нету к нему доступа


Похожие вопросы


  • Показать ещё
    Загружается…

12 июн. 2023, в 21:24

2000 руб./в час

12 июн. 2023, в 21:17

30000 руб./за проект

12 июн. 2023, в 20:59

1000 руб./в час

Минуточку внимания

Use try & catch block to handle errors with PHPMailer in PHP.

use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;
use PHPMailerPHPMailerException;

$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;
    $mail->isSMTP();
    $mail->Host       = 'smtp.example.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'user@example.com';
    $mail->Password   = 'secret';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $mail->Port       = 465;

    //Recipients
    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');

    //Content
    $mail->isHTML(true);
    $mail->Subject = 'Email subject';
    $mail->Body    = 'Your email message';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

You can also use the $mail->ErrorInfo method to display error info from the PHPMailer library.

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

Your comment on this answer:

Понравилась статья? Поделить с друзьями:
  • Как узнать ошибку check engine
  • Как узнать ошибки чека ваз 2110
  • Как узнать ошибки на своем сайте
  • Как узнать ошибки при егэ
  • Как узнать ошибки на ноутбуке