Code Monkey home page Code Monkey logo

laravel-mailbox's Introduction

Laravel Mailbox ๐Ÿ“ฌ

Latest Version on Packagist Total Downloads

Handle incoming emails in your Laravel application.

Mailbox::from('{username}@gmail.com', function (InboundEmail $email, $username) {
    // Access email attributes and content
    $subject = $email->subject();

    $email->reply(new ReplyMailable);
});

Installation

You can install the package via composer:

composer require beyondcode/laravel-mailbox

Usage

Take a look at the official documentation.

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

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

laravel-mailbox's People

Contributors

ankurk91 avatar asantibanez avatar barryvdh avatar clementmas avatar colinmackinlay avatar crishoj avatar davidrushton avatar dniccum avatar emargareten avatar exorus avatar hailwood avatar intellow avatar io238 avatar isarphilipp avatar laravel-shift avatar lbennett-stacki avatar mechelon avatar michael-stokoe avatar mpociot avatar radmen avatar samtlewis avatar sschlein avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-mailbox's Issues

Possibility to use non-mime version for mailgun driver?

When you use an endpoint other than one ending in /mime mailgun sends across a bunch of really useful content in the request - e.g. "trimmed-text" which is the message text without any signatures or similar.

Unfortunately mailgun don't send this information when using a /mime endpoint and instead sends across "mime-body" which we're using to construct the message.

I'm not sure it would be possible but thought I'd float the idea of seeing if we can reconstruct the message from the extended mailgun information rather than the mime version which would give developers easy access to this additional information.

PHP 8 Support

What do you think, @beyondcode?

This seems to be preventing composer from updating for PHP 8 due to composer.json PHP version constraint.

Service Provider Not Registered?

I initially thought this was a composer issue specific to my project and tried everything the internet suggested to reinstall dependencies and clear caches, but I'm still getting a "Class 'App\Providers\Mailbox' not found" error when I attempt to call Mailbox from AppServiceProvider on a brand new Laravel 5.8 project.

It goes away if I let PHPStorm add:
use BeyondCode\Mailbox\Facades\Mailbox;
use BeyondCode\Mailbox\InboundEmail;
But it then reports that it can't find the from method so i suspect it's not a real fix.

The namespaces aren't in the list in config/app.php, so I've tried to add them in there manually too based on the composer.json in the vendor folder, to no avail.

Can anyone reproduce this? Thanks and sorry if I'm missing something basic, which I suspect.

Extending the package model to my own model

Hi there

I can see that I can define a custom model to use in the config file:

    /*
     * The model class to use when converting an incoming email to a message.
     * It must extend the default model class
     */
    'model' => \BeyondCode\Mailbox\InboundEmail::class,

Above is the default model it uses.
I have changed it to:

    /*
     * The model class to use when converting an incoming email to a message.
     * It must extend the default model class
     */
    'model' => Email::class,

Now, I wish to use my own model, because I want to store the e-mails on another table. For this, I have created my own model:

App/Email.php:

namespace App;

use BeyondCode\Mailbox\InboundEmail as InboundEmail;

class Email extends InboundEmail
{
    protected $table = 'emails';
}

However, above gives me below error:

Undefined property: App\Email::$message {"exception":"[object] (ErrorException(code: 0): Undefined property: App\\Email::$message at /Users/Username/Sites/playground/vendor/beyondcode/laravel-mailbox/src/InboundEmail.php:130)

I suspect it is because I don't have the original methods in my own model App/Email.php, that are present in the package model.

Isn't there a way that I can use my own model, by extending the package model, but without copying the content of the package model into my own?

IMAP or POP driver?

Hi!

Didn't see this in the documentation nor in the issues.

Is it just me, or is there no way to open up an IMAP or POP connection to a regular mailbox?

Anyone know of a driver to do that?

Thanks,
Maarten

Running into error while installing mailbox in laravel 6

I'm running into error trying to install laravel-mailbox in my laravel 6 project using composer.
Below are the generated errors
` InvalidArgumentException : Unable to resolve NULL driver for [BeyondCode\Mailbox\MailboxManager].

at C:\wamp64\www\feedpal\vendor\laravel\framework\src\Illuminate\Support\Manager.php:81
77| {
78| $driver = $driver ?: $this->getDefaultDriver();
79|
80| if (is_null($driver)) {

81| throw new InvalidArgumentException(sprintf(
82| 'Unable to resolve NULL driver for [%s].', static::class
83| ));
84| }
85|

Exception trace:

1 Illuminate\Support\Manager::driver()
C:\wamp64\www\feedpal\vendor\beyondcode\laravel-mailbox\src\MailboxManager.php:16

2 BeyondCode\Mailbox\MailboxManager::mailbox()
C:\wamp64\www\feedpal\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php:23`

Laravel 7 compatibility

1.3.0 is not compatible with Laravel 7 due to illuminate/log ^5.7|^5.8|^6.0

@mpociot Could you please release a new version with Laravel 7 compatibility?

Thanks a lot!

Edit: @mpociot sorry I accidentally tagged you on a few unrelated copy/pastes.. I edited them but apologies for pinging you on those

Doesn't seem to be parsing attachments correctly?

With this listener setup

\Mailbox::to('[email protected]', InboundDocumentEmail::class);

And the InboundDocumentEmail::__invoke looking like:

sd($email->text(), $email->html(), $email->attachments());

We're getting some strange behaviour when sending an email

Mail::html('This is the test email contents', function (\Illuminate\Mail\Message $message) {
  $message->to('[email protected]');
  $message->subject('[p1901] This is from an inbound email: ' . now()->toDayDateTimeString());
  $message->from('[email protected]');
  $message->attach(storage_path('logs/.gitignore'));
});

image

Or attaching a csv instead...
image

I've also tried doing actual mailables.
I've got both MAILBOX_DRIVER and MAIL_DRIVER set to log.
Could it be an issue specifically with testing attachments with the log?

Testing driver

Hi there, thanks for the great package!

Is there a dedicated driver for testing?

Supported drivers: "log", "mailgun", "sendgrid", "postmark"

I'm currently using log but it logs all the emails every time I run my tests. It's not necessarily a bug but it's not ideal.

Is there some kind of in-memory array driver available or something similar?

Thanks!

[How-to] setup email inbox on user-based and global level in Laravel5.8 and sendgrid

So, I want to be able to have 2 email inboxes, one for global use (a catch-all) and one for specific user use, like [email protected] and [email protected] etc...

Now, I first of all stumbled over the fact on how I should implement this package... I currently have a Laravel 5.8 application, with the package installed (all default values). In my routes/api.php, I have the following lines added:

Route::post('mailbox/inbound', static function () {
    Mailbox::catchAll(CatchAllMailbox::class);
});

(as stated in the docs).

However, when I send a POST request to http://application.docker/api/mailbox/inbound with the example payload of the sendgrid docs, I just get a 200 response, but nothing hapens (I did set .env variables with the MAILBOX_DRIVER=sendgrid and once to MAILBOX_DRIVER=log.

I'm using a DigitalOcean server, with cloudflare (as DNS).
Below a screenshot of the Cloudflare settings for email:

cloudflare email settings

The configuration for the inbound emails in sendgrid is the following:

Sendgrid inbound configuration

I currently use the staging environment (on my local server) to test the inbound emails).

I tried to follow the installation, and everything worked as intended. However, whatever I do to test the package, I never ever get to receive enything. What am I doing wrong here? Is there somewhere a decent tutorial on how to make an email inbox with this package? I can find alot of tutorials and explainations about how to send, but nowhere on how to receive....

Thank you in advance!

Kindest regards,

Robin

"Incorrect string value" when saving non-UTF-8 emails to MySQL database

Hey there

This issue is mainly as a reference to people coming across the same hair-pulling issue as I did.

When receiving an email in ISO-8859-1 encoding with special characters (such as the danish "รฆรธรฅ") I found that a QueryException will be thrown such as

Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xE6ftet ...' for column 'message' at row 1 (SQL: insert into `mailbox_inbound_emails` (`message`, `message_id`, `subject`, `text`, `from`, `updated_at`, `cr...

This is due to attempting to insert ISO-8859-1 characters into a utf8mb4 MySQL column.

It would be cool if the package had a way to handle this internally - however due to this (hopefully) being a generally rare issue with most clients using UTF-8 I can see why this might not be a priority.

For those interested I solved it by introducing a new method on a custom App\Email model:

<?php

namespace App;

use BeyondCode\Mailbox\InboundEmail;

class Email extends InboundEmail
{
    public function ensureUtf8(): Email
    {
        $encoding = mb_detect_encoding($this->message, ['UTF-8', 'ISO-8859-1']); // Add more encodings to support here

        if ($encoding !== 'UTF-8') {
            $this->message = mb_convert_encoding($this->message, 'UTF-8', $encoding);
            $this->mimeMessage = null;
        }

        return $this;
    }
}

And in my AppServiceProvider@boot

Mailbox::catchAll(function (Email $email) {
   $email->ensureUtf8()->save();
});

Hope this can help somebody else out there :-)

Should we use ->each->delete() to clean emails?

This is a follow on from #20 where I've added support for a custom model.
Currently when cleaning the emails there's no events getting fired as we just do the database query.

This is performant but given this command will normally be run on a cron performance likely isn't an issue and we should instead focus on usability. The trade off of the proposal below of course is that we end up firing 1+n queries instead of just one.

With the events not being fired we obviously cannot detect if a message is being deleted so we are unable to do additional cleanup (such as deleting associated attachments).

I'm proposing we update the code from

InboundEmail::where('created_at', '<', $cutOffDate)->each->delete();

to

InboundEmail::where('created_at', '<', $cutOffDate)->each->delete();

Or if pr #20 is approved

/** @var InboundEmail $modelClass */
$modelClass = config('mailbox.model');
$modelClass::where('created_at', '<', $cutOffDate)->each->delete();

Thoughts?

Unable to resolve NULL driver

Hello,

I can require the package just fine, however when dump-autoload happens I am getting this error:

Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi

   InvalidArgumentException

  Unable to resolve NULL driver for [BeyondCode\Mailbox\MailboxManager].

  at vendor/laravel/framework/src/Illuminate/Support/Manager.php:71
     67โ–•     {
     68โ–•         $driver = $driver ?: $this->getDefaultDriver();
     69โ–•
     70โ–•         if (is_null($driver)) {
  โžœ  71โ–•             throw new InvalidArgumentException(sprintf(
     72โ–•                 'Unable to resolve NULL driver for [%s].', static::class
     73โ–•             ));
     74โ–•         }
     75โ–•

      +13 vendor frames
  14  [internal]:0
      Illuminate\Foundation\Application::Illuminate\Foundation\{closure}()

      +5 vendor frames
  20  artisan:37
      Illuminate\Foundation\Console\Kernel::handle()
Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1

I am using "laravel/framework": "^8.0".

I tried deleting lock files, vendor, clearing cache (wasn't cached initially), nothing happened.

Thanks

Get wrong Parameter

Hello,

I have a problem with the parameter in my inbox handler. The handler is defined as Mailbox::from('{application}@yourname.xyz', SupportMailbox::class);

The SupportMailbox Class simple logs the application parameter:

public function __invoke(InboundEmail $email, $application) 
    {
        Log::debug($application);
    }

Everytime I get postmaster as parameter no matter from which mail address the message was sent. Is there a problem with this package?

Advice for SAAS

Hi there!

This package is awesome, and I can't wait to implement it :)

Currently I am building a SAAS and I want to offer my users a feature to set up an e-mail address to catch incoming e-mails.

What is your advice to do this proper? Implementing this into a SAAS requires to set up the configuration of Mailboxes dynamically. It would be a lack if I'd register all mailboxes on each request (which would require a query every time).

I'd like to have your advice, which might be useful to add to the docs to help future users as well.

Kind regards!

[Docs] How to create a driver ?

@mpociot you did a very great job with Laravel Mailbox.
By building https://github.com/mailcare/mailcare and maintaining https://github.com/php-mime-mail-parser/php-mime-mail-parser, I already dreamt to create this connector for laravel, you did it with a very simple way, easy to use, .... so nice.

Do you have a doc to create a custom driver I would like to try to add the driver mailcare ?

With mailcare (only incoming emails) I can call a webhook like MailGun or SendGrid does:
dwnwhohxqaasmou jpg large

๐Ÿ‘ @mpociot
Have a good day

Installing Mailbox on Lumen 6

I can't install Mailbox on my Lumen 6 project.

Lumen doesn't automaticaly register the provider, then, I did a $app->register(BeyondCode\Mailbox\MailboxServiceProvider::class); in bootstrap/app.php.

But then I get the error

Call to undefined function BeyondCode\Mailbox\config_path()

So I've tried a solution found on the Internet https://gist.github.com/mabasic/21d13eab12462e596120
But then I get the error

Call to undefined method Laravel\Lumen\Routing\Router::aliasMiddleware()

I've also installed https://github.com/laravelista/lumen-vendor-publish to have access to vendor:publish

Now I can't do anything but uninstall all of theses...

how to get it to work with Mailgun? It doesn't work (anymore)

I swear I tested this about 9 months ago and I was able to receive an email through laravel-mailbox. Today I tried it again and this time I am getting Invalid Mailgun signature or timestamp., Url:https://api.redacted.com/laravel-mailbox/mailgun/mime errors

I'm using the HTTP webhook signing key which has to be the right one

I've gone inside the Mailgun Routes and set the forwarding to forward a copy to https://api.redacted.com/laravel-mailbox/mailgun/mime

I've followed the rest of the setup guide and I can't figure out what I'm doing wrong!

Can someone please help me out.. thanks!

In-Reply-To / References

So I was working on Inbound Email last week (what are the odds.. :P), mostly on the proper threading/matching of messages. I see that the reply here is pretty basic still, so would you be open to adding some more headers?

Basically the In-Reply-To header should use the Message-ID of the original message, and the References header should contain the IDs of all previous messages. This will help Gmail etc to match the threads (of the subject is different perhaps).

Also, perhaps set the subject by default?

See for example https://github.com/fruitcake/php-inbound-mail/blob/1799148f2f6f8e4109e995be6849c389c1d3d81c/src/InboundMail.php#L11-L41

On the other way around, it might be useful to expose those headers, so it would be easier to 'thread' them? Eg. determine if it's a reply to a previous message.

Inbound emails not working neither whith Mailgun or SendGrid

I have tested with both Mailgun and SendGrid none of them is receiving emails, With Mailgun when I test the "Send a sample POST" from the dashboard I receive the sample email and stored in the database. But when I use the sam url t with Mailgun routes and I send an email from my Gmail to my domain name email address nothing happens. I have tried both "catchAll" and "from" but got no luck yet. I'm not sure if it's a bug from the library or something wrong with the email service configurations. but if it's configuration I think I should not receive the sample email from Mailgun too.

mailgun - which key am I supposed to use?

I've set up mailgun and I notice that I can receive emails whether I have the public or private key setup

it works in both cases. Actually I suppose you can receive emails without even setting up the key. The key is only for replying?

Is it the public or private key we're supposed to use?

Accessing the ID of an inbound email

Hi,

I'd like to store some incoming mails after parsing them, but I'd like to have a reference to them in the data I create from the parsed mail. IE the model ID the InboundEmail model that I get in my Mailbox (not the mail ID).

The InboundEmail is not yet persisted once it reaches my mailbox, is there any issues with calling $inboundEmail->save(); within the mailbox?
This would allow me to get the ID and store the reference to the raw mail.

Cheers,

Create an inbox via my Mail server

I want to draw my inbox with Pop3 to the table on my website. I have read the documentation, but I could not understand how to run it.
Do you have any sample? or is there anyone who can help?

Mailgun webhook doesn't work

If I try to test webhook via mailgun, it's getting an exception:
I'm trying this via ngrok proxy, and this is what i'm getting as a response.

ErrorException: hash_equals(): Expected known_string to be a string, array given in file /var/www/html/vendor/beyondcode/laravel-mailbox/src/Http/Requests/MailgunRequest.php on line 51
Stack trace:
  1. ErrorException-&gt;() /var/www/html/vendor/beyondcode/laravel-mailbox/src/Http/Requests/MailgunRequest.php:51
  2. hash_equals() /var/www/html/vendor/beyondcode/laravel-mailbox/src/Http/Requests/MailgunRequest.php:51
  3. BeyondCode\Mailbox\Http\Requests\MailgunRequest-&gt;verifySignature() /var/www/html/vendor/beyondcode/laravel-mailbox/src/Http/Requests/MailgunRequest.php:31
  4. BeyondCode\Mailbox\Http\Requests\MailgunRequest-&gt;BeyondCode\Mailbox\Http\Requests\{closure}() /var/www/html/vendor/laravel/framework/src/Illuminate/Validation/Validator.php:253
  5. call_user_func_array() /var/www/html/vendor/laravel/framework/src/Illuminate/Validation/Validator.php:253

And this is what i get when i dump mailgun response from MailgunRequest class (my private data like tokens and domain keys were changed to "XXX").
In validator() method i do var_dump($this->all());exit;

Response: array(2) {
    ["signature"]=>
  array(3) {
        ["timestamp"]=>
    string(10) "1567593293"
        ["token"]=>
    string(50) "xxx"
        ["signature"]=>
    string(64) "xxx"
  }
  ["event-data"]=>
  array(14) {
        ["tags"]=>
    array(2) {
            [0]=>
      string(8) "my_tag_1"
            [1]=>
      string(8) "my_tag_2"
    }
    ["timestamp"]=>
    float(1521472262.9082)
    ["storage"]=>
    array(2) {
            ["url"]=>
      string(110) "https://se.api.mailgun.net/v3/domains/sandboxXXX.mailgun.org/messages/message_key"
            ["key"]=>
      string(11) "message_key"
    }
    ["envelope"]=>
    array(4) {
            ["sending-ip"]=>
      string(14) "209.61.154.250"
            ["sender"]=>
      string(55) "[email protected]"
            ["transport"]=>
      string(4) "smtp"
            ["targets"]=>
      string(17) "[email protected]"
    }
    ["recipient-domain"]=>
    string(11) "example.com"
        ["id"]=>
    string(22) "XXX"
        ["campaigns"]=>
    array(0) {
        }
    ["user-variables"]=>
    array(2) {
            ["my_var_1"]=>
      string(19) "Mailgun Variable #1"
            ["my-var-2"]=>
      string(7) "awesome"
    }
    ["flags"]=>
    array(4) {
            ["is-routed"]=>
      bool(false)
      ["is-authenticated"]=>
      bool(true)
      ["is-system-test"]=>
      bool(false)
      ["is-test-mode"]=>
      bool(false)
    }
    ["log-level"]=>
    string(4) "info"
        ["message"]=>
    array(3) {
            ["headers"]=>
      array(4) {
                ["to"]=>
        string(25) "Alice <[email protected]>"
                ["message-id"]=>
        string(78) "[email protected]"
                ["from"]=>
        string(61) "Bob <[email protected]>"
                ["subject"]=>
        string(22) "Test delivered webhook"
      }
      ["attachments"]=>
      array(0) {
            }
      ["size"]=>
      int(111)
    }
    ["recipient"]=>
    string(17) "[email protected]"
        ["event"]=>
    string(9) "delivered"
        ["delivery-status"]=>
    array(9) {
            ["tls"]=>
      bool(true)
      ["mx-host"]=>
      string(19) "smtp-in.example.com"
            ["attempt-no"]=>
      int(1)
      ["description"]=>
      NULL
      ["session-seconds"]=>
      float(0.43319892883301)
      ["utf8"]=>
      bool(true)
      ["code"]=>
      int(250)
      ["message"]=>
      string(2) "OK"
            ["certificate-verified"]=>
      bool(true)
    }
  }
}

Advice for extending

Hey - I started, extending this package into nova as a model and resource called Enquiry.. I needed some extra custom fields like "reference" "status" etc.. so I added these in the migration and started setting up the details and index views..

I've just come across an issue though when trying to save an Enquiry without any mail content:
Undefined property: App\Enquiry::$message
.../vendor/beyondcode/laravel-mailbox/src/InboundEmail.php#136

I just wanted to check am I extending this correctly? or would the neater behaviour have been to have a separate model / resource for Enquiry and set a relationship to a new Enquiry within the MyMailbox __invoke ?

Thanks

SendGrid webhooks not resolving

Hi, I am currently migrating an application from using Mailgun to SendGrid. To be clear everything was working as desired using Mailgun, but as soon as I switched, nothing has worked since. The emails are clearly going somewhere because they are not being rejected. However the webhooks are not firing.

Any help would be appreciated.

I have followed everything in the documentation to a "T":

My ENV variables

MAILBOX_DRIVER=sendgrid
MAILBOX_HTTP_PASSWORD=password
MAILBOX_DOMAIN="parse.mail.cultivateprm.com"

Inbound Parse configuration

Screen Shot 2021-01-23 at 9 09 30 PM

DNS settings within GoDaddy

Screen Shot 2021-01-23 at 9 11 39 PM

Incoming "to" not working

I'm trying to get this setup using an incoming "to" as such:

Mailbox::to('{uuid}@mydomain.com', DefaultMailbox::class);

The mailbox was never matching, so I created a catch all to test it out:

Mailbox::catchAll(CatchAllMailbox::class);

The catch all seems to be working but the email does not seem to be parsed correctly.

Contents of CatchAllMailbox.php

<?php

namespace App\Mailboxes;

use BeyondCode\Mailbox\InboundEmail;

class CatchAllMailbox
{
    public function __invoke(InboundEmail $email)
    {
        logger($email->id());
        logger($email->to());
        logger($email->from());
        logger($email->subject());
        logger('=====================================');
    }
}

Log Result

[2019-02-19 11:34:57] local.DEBUG: [email protected]  
[2019-02-19 11:34:57] local.DEBUG: array (
)  
[2019-02-19 11:34:57] local.DEBUG: [email protected]  
[2019-02-19 11:34:57] local.DEBUG: =====================================  
[2019-02-19 11:38:10] local.DEBUG: [email protected]  
[2019-02-19 11:38:10] local.DEBUG: array (
)  
[2019-02-19 11:38:10] local.DEBUG: [email protected]  
[2019-02-19 11:38:10] local.DEBUG: =====================================  

The to list seems to be empty, however if i take the stored message from the database and decode the base64 I can see the recipient field is set to [email protected]

IMAP Driver

Hi there!

This package looks really cool and promising :)

I'd like to use this tool for my clients in my SAAS. However, most of them will not be able to manage their DNS settings to set up a service like Sengrid. For them it would be easier (and more secure in my opinion) to enter an IMAP configuration.

Can you give me any direction? This is not possible at the moment right? And, I probably would need to create a custom driver, right?

Since you'd need to do an active request towards IMAP (instead of having a webhook), this would need another approach I am afraid, which is totally out of scope of this library...

EDIT: The best solution that came up in my mind: we could use the webhook (like all drivers do) to do a 'pull' from the IMAP mailbox. The webhook should be triggered using a cron (like cron-job.org). This way we keep it the way most drivers work.

Regards, Bob

Extending the save method

Hi

I have defined my own model called Email, that is extending the default InboundEmail model.

I can see in the Routing/Router.php file, the save() method is like this:

protected function storeEmail(InboundEmail $email)
{
     $email->save();
}

Now in my Email model, I:

  • Have extended it to use a new table.
  • Is setting a custom variable, in order to "combine" it to a relationship.

In my AppServiceProvider, I am passing the custom variable (token) to my Model:

//AppServiceProvider:
Mailbox::to('{token}@myapp.com', Email::class);

Email.php:

    protected $table = 'emails';

    public function __invoke(InboundEmail $email, $token)
    {
        $email->stream_token = $token;
    }

    /**
     * An email belongs to a Stream.
     */
    public function stream()
    {
        return $this->belongsTo(Stream::class, 'stream_token');
    }

Now my question is: how can I extend the save method, so I can check if the relationship exists in the database before persiting it?

Because my code will fail (500 internal server error), if I send an email to an internal email, but where the {token) does not exist in the database.

Can I do something like this in my Email.php model:

protected function storeEmail(InboundEmail $email, $token)
{
     if($email->stream->exists()){
     $email->stream_token = $token;
     $email->save();
     }else{
      Log::debug('Invalid "to" token. It does not exist in our system');
     
    }
}

Alternative 'To' headers?

For some automated emails (leads) a single mail is in [email protected], but my trigger is for example [email protected]. Would it be possible to parse X-Forwarded-To before it was routed to a mailbox? (Eg. an event/filter/callback to modify it manually).

Or should I just create a fallback/catch-all that routes it when To fails?

Access to Postmark StrippedTextReply

Is there a way I can extend mailbox to save the StrippedTextReply from postmarks json.
Or am I best calling postmarks api with a matched Message-ID header to then access this?

If I have to do it with the latter is there an easy way to save postmarks MessageID (different from their header Message-ID) in the inbound mail table separately? as the message id passed at the moment is the one that has come from the senders gmail for example.

Thanks

Spam filtering

Hi,

Is there any kind of inbound spam filtering? Since now when you do a catchall, the inbox is full of junk....

Queue getQueuableId issue

Thanks for this package.

I was running into this exception

BeyondCode\Mailbox\InboundEmail::id must return a relationship instance.
[stacktrace]
#0 vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php(397): Illuminate\\Database\\Eloquent\\Model->getRelationshipFromMethod('id')
#1 vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php(327): Illuminate\\Database\\Eloquent\\Model->getRelationValue('id')
#2 vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1388): Illuminate\\Database\\Eloquent\\Model->getAttribute('id')
#3 vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1398): Illuminate\\Database\\Eloquent\\Model->getKey()
#4 vendor/laravel/framework/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php(32): Illuminate\\Database\\Eloquent\\Model->getQueueableId()
#5 vendor/laravel/framework/src/Illuminate/Queue/SerializesModels.php(23): App\\Jobs\\ProcessInboundEmail->getSerializedPropertyValue(Object(BeyondCode\\Mailbox\\InboundEmail))

When running

Mailbox::catchAll(function (InboundEmail $email) {
    dispatch(new ProcessInboundEmail($email));
});

I see this is because the email model is only saved at the end of any Mailbox routes, so there is no id to serialize for queued jobs.

I can fix this by updating the queued job to the following, but wanted to check if you'd accept a PR to match Mailbox routes first then call storeEmail before running any routes?

Mailbox::catchAll(function (InboundEmail $email) {
    $email->save();
    dispatch(new ProcessInboundEmail($email));
});

Thanks :)

Not really an issue more of a question

Does the Mailbox package allow multiple emails?

Meaning within my application there could 1000s of users all with different emails they want to catch incoming and outgoing etc.

Company A - may have X amount of users using companyA.com as their emails
Company B - may have X amount of users using companyB.com as their emails

Does the package allow for this?

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.