如何在laravel中全局检测邮件是否已发送并全局存储邮件通知日志和异常存储?

问题描述 投票:0回答:2

我正在创建一个 web 应用程序并通过 laravel 邮件助手功能发送一堆电子邮件(代码在下面给出),现在我想存储每封邮件的日志,包括所有内容。即电子邮件主题、收件人、密件抄送。在我的本地数据库中显示管理员。但是代码很旧,所以在很多地方都使用了邮件助手功能,但我想只在一个地方实现它。在 laravel 中有可能吗?查看我用来在每个地方发送邮件和存储日志的代码。

Mail::to($to)-\>cc($bcc)-\>send(new \\App\\Mail\\Mailer($maildata));
php laravel email backend helper
2个回答
0
投票

你可以使用 Laravel 内置的事件系统和日志系统。

首先,您需要定义一个事件监听器来监听 Illuminate\Mail\Events\MessageSending 事件。此事件在电子邮件消息发送之前触发,因此它是记录电子邮件数据的理想场所。

namespace App\Listeners;

use Illuminate\Mail\Events\MessageSending;
use Illuminate\Support\Facades\Log;

class LogSentEmails
{
    /**
     * Handle the event.
     *
     * @param  \Illuminate\Mail\Events\MessageSending  $event
     * @return void
     */
    public function handle(MessageSending $event)
    {
        $message = $event->message;

        $to = implode(', ', array_keys($message->getTo()));
        $cc = implode(', ', array_keys($message->getCc()));
        $bcc = implode(', ', array_keys($message->getBcc()));
        $subject = $message->getSubject();
        $body = $message->getBody();

        Log::info("Email sent to: $to; CC: $cc; BCC: $bcc; Subject: $subject; Body: $body");
    }
}

此事件侦听器将记录收件人的电子邮件地址、CC 电子邮件地址、BCC 电子邮件地址、主题和电子邮件正文。

接下来,您需要在您的 EventServiceProvider 中注册事件监听器。

protected $listen = [
        MessageSending::class => [
            LogSentEmails::class,
        ],
    ];

最后,您可以使用 Laravel 内置的日志系统来记录邮件发送过程中发生的任何异常。您可以在 config/logging.php 中定义邮件日志通道:

'channels' => [
    // ...

    'mail' => [
        'driver' => 'daily',
        'path' => storage_path('logs/mail.log'),
        'level' => 'info',
        'days' => 14,
    ],

    // ...
],

还通过以下方式记录任何错误:

try {
    Mail::to($to)->cc($bcc)->send(new \App\Mail\Mailer($maildata));
} catch (\Exception $e) {
    \Log::channel('mail')->error($e);
}

-1
投票

如果 Mail 是 PEAR 的 Mail:: 接口,那么 ->send 在成功发送时返回 true,否则返回 false。如果邮件通信中出现一些错误,例如。与格式错误的标题相关,你有一个梨错误。 考虑到这一点,您可以访问 Mail 对象并在对象内部找到您需要的内容。

检查这个小函数作为起点:它使用 Mail Pear 类

function send_generic_mail( $to = "", $subject = "", $body = "", $allegati = array(), $bcc = "" ) {
 require_once "{$_SERVER['DOCUMENT_ROOT']}/application/third_party/Mail.php";
 require_once "{$_SERVER['DOCUMENT_ROOT']}/application/third_party/Mail/mime.php";
 $headers = array (
    'From' => "{$this->config->config["website_name"]} <{$this->config->config["generic_email"]}>",
    'To' => $to,
    'Subject' => $subject 
 );
if (trim( $bcc ) !== "") {
    $headers [ "Bcc" ] = $bcc;
}
/**
 * Configuration for ssl
 */
if ($this->config["mail_protocol"] == "ssl"){
    $socket_options =  array (
                "ssl" => array (
                "verify_peer" => false,
                "verify_peer_name" => false,
                "allow_self_signed" => true 
                ) 
            );
} else {
    $socket_options = "";
}
$smtp = Mail::factory( 'smtp', array (
        "host" => "{$this->config["mail_protocol"]}://{$this->config["mail_host"]}",
        "port" => "{$this->config["mail_port"]}",
        "auth" => true,
        "username" => "{$this->config["mail_username"]}", // your gmail account
        "password" => "{$this->config["mail_password"]}", // your password
        "debug" => false,
        $socket_options
) );
$nohtml = strip_tags( $body );
$mime = new Mail_mime();
$mime->setTXTBody( $nohtml );
$mime->setHTMLBody( $body );
// Attachments //
if (sizeof( $allegati )) {
    foreach ( $allegati as $file ) {
        $mime->addAttachment( $file->name, "application/octet-stream", $file->attach_name );
    }
}
$body = $mime->get();
// the 2nd parameter allows the header to be overwritten
// @see http://pear.php.net/bugs/18256
$headers = $mime->headers( $headers, true );
// Send the mail
$smtp->send( $to, $headers, $body );
return $smtp;
}
© www.soinside.com 2019 - 2024. All rights reserved.