Php send all errors to email

Обработка ошибок с помощью PHPMailer

Я пытаюсь использовать PHPMailer для небольшого проекта, но я немного запутался в обработке ошибок с помощью этого программного обеспечения. Надеюсь, что у кого-то есть опыт. Когда я настроил электронную почту, и я использую:

$result = $mail->Send(); if(!$result) < // There was an error // Do some error handling things here >else

Который работает отлично, более или менее. Проблема в том, что есть ошибка, PHPMailer также, похоже, повторяет ошибку, поэтому, если есть проблема, она просто отправляет эту информацию непосредственно в браузер, по сути, нарушая любую обработку ошибок, которую я пытаюсь сделать.

Есть ли способ заставить замолчать эти сообщения? Он не бросает исключение, просто распечатывает ошибку, которая в моем тестовом примере:

invalid address: @invalid@email You must provide at least one recipient email address. 

Он должен быть ошибкой, но он должен находиться в $ mail-> ErrorInfo; не будучи эхо-программным обеспечением.

PHPMAiler использует Исключения. Попробуйте принять следующий код :

require_once '../class.phpmailer.php'; $mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch try < $mail->AddReplyTo('name@yourdomain.com', 'First Last'); $mail->AddAddress('whoto@otherdomain.com', 'John Doe'); $mail->SetFrom('name@yourdomain.com', 'First Last'); $mail->AddReplyTo('name@yourdomain.com', 'First Last'); $mail->Subject = 'PHPMailer Test Subject via mail(), advanced'; $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically $mail->MsgHTML(file_get_contents('contents.html')); $mail->AddAttachment('images/phpmailer.gif'); // attachment $mail->AddAttachment('images/phpmailer_mini.gif'); // attachment $mail->Send(); echo "Message Sent OK\n"; > catch (phpmailerException $e) < echo $e->errorMessage(); //Pretty error messages from PHPMailer > catch (Exception $e) < echo $e->getMessage(); //Boring error messages from anything else! > 

Просто нужно было это исправить. Вышеприведенные ответы, похоже, не учитывают $mail->SMTPDebug = 0; вариант. Возможно, он не был доступен, когда вопрос был задан первым.

Читайте также:  Пример работы CSS

Если вы получили свой код с сайта PHPMail, по умолчанию будет $mail->SMTPDebug = 2; // enables SMTP debug information (for testing) $mail->SMTPDebug = 2; // enables SMTP debug information (for testing)

Установите значение 0 для подавления ошибок и отредактируйте часть «catch» вашего кода, как описано выше.

Пожалуйста, обратите внимание. Вы должны использовать следующий формат при создании PHPMailer!

Если вы не делаете исключений, игнорируются, и единственное, что вы получите, – это эхо от рутины! Я знаю, что это хорошо после того, как это было создано, но, надеюсь, это поможет кому-то.

Вы можете получить дополнительную информацию об ошибке с помощью метода $mail->ErrorInfo . Например:

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

Это альтернатива модели исключения, которую нужно активировать с помощью new PHPMailer(true) . Но если можно использовать модель исключения, используйте ее как @Phil Rykoff.

Это происходит с главной страницы PHPMailer по github https://github.com/PHPMailer/PHPMailer .

Мы написали класс-оболочку, который захватывает буфер и преобразует печатный результат в исключение. это позволяет нам обновлять файл phpmailer, не задумываясь о том, чтобы комментировать события echo при каждом обновлении.

Класс-оболочка имеет методы:

public function AddAddress($email, $name = null) < ob_start(); parent::AddAddress($email, $name); $error = ob_get_contents(); ob_end_clean(); if( !empty($error) ) < throw new Exception($error); >> 

Даже если вы используете исключения, он все равно выводит ошибки.
Вы должны установить $ MailerDebug в False, который должен выглядеть так

$mail = new PHPMailer(); $mail->MailerDebug = false; 
use try < as above use Catch as above but comment out the echo lines >catch (phpmailerException $e) < //echo $e->errorMessage(); //Pretty error messages from PHPMailer > catch (Exception $e) < //echo $e->getMessage(); //Boring error messages from anything else! > 

В PHPMailer.php есть строки, как показано ниже:

Просто прокомментируйте эти строки, и вам будет хорошо идти.

$mail = new PHPMailer(); $mail->AddAddress($email); $mail->From = $from; $mail->Subject = $subject; $mail->Body = $body; if($mail->Send())< echo 'Email Successfully Sent!'; >else

самый простой способ обработки электронной почты успешно или неудачно …

Источник

Laravel Send an Email on Error Exceptions Tutorial

I am going to show you example of laravel send email on exception. step by step explain laravel send exception mail. if you have question about how to send mail on exception in laravel then I will give simple example with solution. you can see laravel send email on error.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10 version.

Sometimes we upload code on production and when you have any error on production then we don’t know it. Even laravel log on laravel.log file but as a developer, we don’t check every day on the log file. so you need something that will inform you when error or exception generate on your application. I will give you the perfect solution for this. When any error or exception generate in your laravel project then it will inform you via email. Yes, We will send an email on Error Exceptions in laravel.

It’s totally free. So just follow the below step and add send mail on an error in laravel app.

Step 1: Install Laravel

This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Make Configuration

In first step, you have to add send mail configuration with mail driver, mail host, mail port, mail username, mail password so laravel 9 will use those sender configuration for sending email. So you can simply add as like following.

MAIL_MAILER=smtp

MAIL_HOST=smtp.gmail.com

MAIL_PORT=465

MAIL_USERNAME=mygoogle@gmail.com

MAIL_PASSWORD=rrnnucvnqlbsl

MAIL_ENCRYPTION=tls

MAIL_FROM_ADDRESS=mygoogle@gmail.com

MAIL_FROM_NAME=»$»

Step 3: Create Mail Class

In this step we will create mail class ExceptionOccured for email send on error exception. So let’s run bellow command.

php artisan make:mail ExceptionOccured

now, let’s update code on ExceptionOccured.php file as bellow:

namespace App\Mail;

use Illuminate\Bus\Queueable;

use Illuminate\Contracts\Queue\ShouldQueue;

use Illuminate\Mail\Mailable;

use Illuminate\Queue\SerializesModels;

class ExceptionOccured extends Mailable

use Queueable, SerializesModels;

public $content;

/**

* Create a new message instance.

*

* @return void

*/

public function __construct($content)

$this->content = $content;

>

/**

* Build the message.

*

* @return $this

*/

public function build()

return $this->view(’emails.exception’)

->with(‘content’, $this->content);

>

>

Step 4: Create Blade View

In this step, we will create blade view file for email. In this file we will write all exception details. now we just write some dummy text. create bellow files on «emails» folder.

>

ErrorException

>

>

>

in >»>>>(in > line >

@endforeach

Step 5: Send Mail on Exception

Here, every error exception handle on Exceptions/Handler.php file in laravel. in this file we will write code for send email with error message, file, line, trace, url and ip address details. you can get more details and send in email.

You can also store this information on database from here. so let’s copy below code and paste on Handler.php file. You need to change recipient email address.

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

use Throwable;

use Log;

use Mail;

use App\Mail\ExceptionOccured;

class Handler extends ExceptionHandler

/**

* A list of the exception types that are not reported.

*

* @var array>

*/

protected $dontReport = [

];

/**

* A list of the inputs that are never flashed for validation exceptions.

*

* @var array

*/

protected $dontFlash = [

‘current_password’,

‘password’,

‘password_confirmation’,

];

/**

* Register the exception handling callbacks for the application.

*

* @return void

*/

public function register()

$this->reportable(function (Throwable $e) $this->sendEmail($e);

>);

>

/**

* Write code on Method

*

* @return response()

*/

public function sendEmail(Throwable $exception)

try

$content[‘message’] = $exception->getMessage();

$content[‘file’] = $exception->getFile();

$content[‘line’] = $exception->getLine();

$content[‘trace’] = $exception->getTrace();

$content[‘url’] = request()->url();

$content[‘body’] = request()->all();

$content[‘ip’] = request()->ip();

Mail::to(‘your_email@gmail.com’)->send(new ExceptionOccured($content));

> catch (Throwable $exception) Log::error($exception);

>

>

>

Step 6: Create Routes

In this step, we will add one route that generate exception and you will receive one email notification. We are creating this is a testing route. so let’s add it.

use Illuminate\Support\Facades\Route;

/*

|—————————————————————————

| Web Routes

|—————————————————————————

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the «web» middleware group. Now create something great!

|

*/

Route::get(‘/get-error’, function ()

$find = App\Models\User::find(100000)->id;

return view(‘welcome’);

>);

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/get-error

Output: You Email Look Like This

Источник

Laravel 10 Send an Email on Error Exceptions Tutorial

If you have deployed your Laravel web application on a live server and want to receive email notifications whenever an error occurs, you can utilize Laravel’s App\Exceptions\Handler class. This tutorial will guide you through the process of setting up error exception email notifications in your Laravel application.

In this tutorial, you will learn how to set up error exception mail notifications in your Laravel application. This will allow you to receive email notifications whenever an error occurs in your application, ensuring that you are promptly alerted to any issues.

Laravel 10 Send an Email on Error Exceptions Tutorial

  • Step 1: Create Mail Class
  • Step 2: Create an Email View
  • Step 3: Configure Handler.php File for Exception Mail

Step 1: Create Mail Class

First of all, create a mail class using the below command:

php artisan make:mail ExceptionMail

This will create a class ExceptionMail in the app/Mail directory.

content = $content; > /** * Build the message. * * @return $this */ public function build() < return $this->view('emails.exception_email') ->with('content', $this->content); > >

Step 2: Create an Email View

Now, we will create a new view file inside the emails folder that file name email_exception.blade.php. and the below-given code in add your email_exception.blade.php file:

Step 3: Configure Handler.php File for Exception Mail

Go to App\Exceptions\Handler file and update the below code into your file.

shouldReport($exception)) < $this->sendEmail($exception); // sends an email > parent::report($exception); > /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $exception * @return \Illuminate\Http\Response */ public function render($request, Exception $exception) < return parent::render($request, $exception); >public function sendEmail(Throwable $exception) < try < $e = FlattenException::create($exception); $handler = new SymfonyExceptionHandler(); $html = $handler->getHtml($e); Mail::to('[email protected]')->send(new ExceptionMail($html)); > catch (Exception $ex) < dd($ex); >> >

Replace ‘[email protected]’ with the email address where you want to receive error notifications.

Now, whenever an error occurs in your Laravel application, Laravel will automatically trigger the report method in the Handler class. This method will send an email containing the error details to the specified email address.

Make sure you have configured a mail driver in your Laravel application’s .env file or the config/mail.php file to enable email sending.

Conclusion

With this setup, you will receive an email notification whenever an error occurs in your Laravel web application on the live server. This can help you promptly identify and address any issues that may arise.

Источник

Оцените статью