skip to Main Content

I’m creating one webapp and sending bunch of emails through laravel Mail helper function (code is given below), Now i want to store the log each mails including everything. i.e. email subject, recipients, bcc. in my local database to display admin. but code is old so at many places the mail helper function is used, but I want to achieve it at doing at only one place. Is it possible in laravel? see the code I’m using to send mail and store log at every places.

Mail::to($to)->cc($bcc)->send(new \App\Mail\Mailer($maildata));

2

Answers


  1. If Mail is PEAR’s Mail:: interface, then ->send returns true on successfull delivery or false otherwise. If there are some errors in the mail communication, eg. related to malformed headers, you have a Pear Error.
    Having this in your mind, you can access the Mail object and find what you need inside the object himself.

    Check this little function as a starting points: it uses Mail Pear class

    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;
    }
    
    Login or Signup to reply.
  2. You can use Laravel’s built-in event system and logging system.

    First, you need to define an event listener that will listen for the IlluminateMailEventsMessageSending event. This event is triggered just before the email message is sent, so it’s the perfect place to log the email data.

    namespace AppListeners;
    
    use IlluminateMailEventsMessageSending;
    use IlluminateSupportFacadesLog;
    
    class LogSentEmails
    {
        /**
         * Handle the event.
         *
         * @param  IlluminateMailEventsMessageSending  $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");
        }
    }
    

    This event listener will log the recipient’s email addresses, CC email addresses, BCC email addresses, subject, and body of the email message.

    Next, you need to register the event listener in your EventServiceProvider.

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

    Finally, you can use Laravel’s built-in logging system to log any exceptions that occur during email sending. You can define a Mail log channel in your config/logging.php:

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

    Also log any errors in the following way:

    try {
        Mail::to($to)->cc($bcc)->send(new AppMailMailer($maildata));
    } catch (Exception $e) {
        Log::channel('mail')->error($e);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search