GithubHelp home page GithubHelp logo

henryavila / laravel-nova-email-tracking Goto Github PK

View Code? Open in Web Editor NEW
1.0 1.0 0.0 105 KB

Allow Every e-mail sent by Laravel be tracked using Mailgun webhooks and display these emails on Laravel Nova Dashboard. Also, it allow to track the e-mail sender, as any model

License: MIT License

PHP 99.84% Blade 0.16%

laravel-nova-email-tracking's Introduction

Rastreamento de e-mail Integrado ao Laravel Nova

This is a fork of henryavila/email-tracking package. The original package droped support of Laravel Nova. This package was created to keep support for Laravel Nova. This package will not receite update, since I moved from Laravel Nova to Filament


Mailgun configuration

On mailgun interface, add a webhook to the url APP_URL/webhooks/mailgun

Installation

Setup Laravel Mail with mailgun at https://laravel.com/docs/master/mail#mailgun-driver

Define the environments variable in your .env file

MAIL_MAILER=mailgun
MAILGUN_DOMAIN=yourdomain.com
MAILGUN_SECRET=key-99999999999999999999999999999999

Install the package via composer:

composer require henryavila/laravel-nova-email-tracking

Publish and run the migrations with:

php artisan vendor:publish --tag="laravel-nova-email-tracking-migrations"
php artisan migrate

Publish the config file with:

php artisan vendor:publish --tag="laravel-nova-email-tracking-config"

This is the contents of the published config file:

return [
    /**
     * if defined, the Email model will use this database connection.
     * This connection name must be defined in database.connections config file
     */
    'email-db-connection' => null,

    /**
     * Save the HTML Body of all sent messages
     */
    'log-body-html' => true,

    /**
     * Save the TXT Body of all sent messages
     */
    'log-body-txt' => true,
];

``


Publish the lang files (optional) with:

```bash
php artisan vendor:publish --tag="laravel-nova-email-tracking-translations"

Configuration

On NovaServiceProvider.php, add the code:

    /**
     * Get the tools that should be listed in the Nova sidebar.
     *
     * @return array
     */
    public function tools()
    {
        \HenryAvila\LaravelNovaEmailTracking\Nova\LaravelNovaEmailTrackingTool::make()
    }

This will display the e-mails on Laravel Nova Dashboard.

If you need to customize the Nova Resource, just create a new one extending HenryAvila\LaravelNovaEmailTracking\Nova\EmailResource and use this code

    /**
     * Get the tools that should be listed in the Nova sidebar.
     *
     * @return array
     */
    public function tools()
    {                    
        \HenryAvila\LaravelNovaEmailTracking\Nova\LaravelNovaEmailTrackingTool::make()
            ->emailResource(CustomEmailResource::class)                        
    }                

On all models that can send e-mail, and add the trait ModelWithEmailsSenderTrait

On EventServiceProvider.php, add the code

   /**
     * The event listener mappings for the application.
     *
     * @var array
     */
   protected $listen = [
        \Illuminate\Mail\Events\MessageSent::class => [
            \HenryAvila\LaravelNovaEmailTracking\Listeners\LogEmailSentListener::class,
        ],
   ];

At this point, all e-mail sent from app, will be logged on the app, but the sender will not be saved

Save the Email sender

To be able to track the e-mail sender, you must create a custom Mailable or Notification. the default mail can't define the sender (like Nova Reset password e-mail)

Mailable

When creating a new Mailable, overwrite the Base Mailable Class with HenryAvila\LaravelNovaEmailTracking\Mail\TrackableMail

This default code:

class SampleMail extends \Illuminate\Mail\Mailable
{
	public function build()
	{
		return $this->view('emails.sample');
	}
}

must be overwritten by this one:

class SampleMail extends \HenryAvila\LaravelNovaEmailTracking\Mail\TrackableMail
{
    public function __construct(public \Illuminate\Database\Eloquent\Model $model)
    {
        parent::__construct($model, 'emails.sample');
    }
    
    public function build()
	{
		// Normal build without call to the view() method
	}
}

Basically, remove the view declaration from build() and move it to constructor.

Ps: In this sample, 'emails.sample' is the name of the view generated for this sample. Overwrite it with it with yours.

This new code will pass in the constructor the model that is the email sender. At this point, in build() method, you can continue to setup the mailable, but know that the view is already defined. If you call the view method again, the sender configuration will be overwritten.

To send the Mailable, just pass the model in the mailable constructor

// example: Send the Sample Mail to User with id 1
$user = User::find(1);
Mail::to($user)->send(new App\Mail\SampleMail($user));

Notification

When creating a notification, all you have to do is to change the toMail() method. Replace the default code:

public function toMail($notifiable): MailMessage
{
    return (new MailMessage)
        ->line('The introduction to the notification.')
        ->action('Notification Action', url('/'))
        ->line('Thank you for using our application!');
}

with this code:

public function __construct(public \Illuminate\Database\Eloquent\Model $model)
{
    //
}

public function toMail($notifiable): MailMessage
{
    return (new \HenryAvila\LaravelNovaEmailTracking\Notifications\TrackableNotificationMailMessage($this->model))
        ->line('The introduction to the notification.')
        ->action('Notification Action', url('/'))
        ->line('Thank you for using our application!');
}

To send the notification

// User with id 1 send the sample notification to multiple $clientes
$user = User::find(1);
Notification::send($clientes, new SampleNotification($user));

Displaying the e-mails from sender

To be able to display the e-mails sent from a send, add this code in the fields() method on nova resource

public function fields(Request $request)
{
    return [
        ...
        \HenryAvila\LaravelNovaEmailTracking\LaravelNovaEmailTracking::hasManyEmailsField(),
        ...
    ];
}

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

laravel-nova-email-tracking's People

Contributors

henryavila avatar dependabot[bot] avatar github-actions[bot] avatar

Stargazers

Bartłomiej Gajda avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.