4

I'm sending an email in Laravel via SendGrid using the configuration suggested in SendGrid's docs.

Just to provide an example of how it looks now:

Mail::send('emails.demo', $data, function($message)
{
    $message->to('jane@example.com', 'Jane Doe')->subject('This is a demo!');
});

The email itself works fine, but I'd like to add a SendGrid category. I've accomplished this in past non-Laravel projects using the addCategory() method in this repo.

My question: Is there an easy way to add a SendGrid category just using the Laravel mail library, or does it make more sense to just use the SendGrid PHP library?

Ben Chamberlin
  • 671
  • 4
  • 18

3 Answers3

2

I would just use the library, even though it isn't that pretty.

Daniel Payne
  • 125
  • 8
  • 2
    That's what I wound up going with. Realized I was bending over backwards just to save myself like 3 lines of code. – Ben Chamberlin Oct 22 '15 at 23:34
  • For those who prefer to not add a library for this feature alone, see this if you're using SMTP: https://stackoverflow.com/a/42780012/1849081 – Saneem Apr 02 '18 at 07:56
2

There are two different ways of doing this depending on your MAIL_MAILER (or MAIL_DRIVER in Laravel <7).

When MAIL_DRIVER=smtp:

    public function build()
    {
        return $this->view('mail')
            ->from('')
            ->subject('')
            ->withSwiftMessage(function($message) {
                $message->getHeaders()->addTextHeader(
                    'X-SMTPAPI', json_encode(['category' => 'testing category'])
                );
            });
    }

Read more about the smtp driver: https://docs.sendgrid.com/for-developers/sending-email/laravel#adding-a-category-or-custom-field

When MAIL_DRIVER=sendgrid:

   use Sichikawa\LaravelSendgridDriver\SendGrid;

    public function build()
    {
        return $this->view('mail')
            ->from('')
            ->subject('')
            ->sendgrid(['category' => 'testing category']);
    }

Read more about the sendgrid driver: https://github.com/s-ichikawa/laravel-sendgrid-driver

Fredrik
  • 3,027
  • 8
  • 33
  • 66
Tycho
  • 131
  • 1
  • 5
  • Works for me. This should be the correct answer. Sendgrid now have a laravel page too. – mwal Jun 19 '19 at 16:38
  • Nice they added it to their documentation https://sendgrid.com/docs/for-developers/sending-email/laravel/ I had contact with sengrid to get to this solution great help from their side! – Tycho Jun 21 '19 at 09:21
  • Just a heads up that Laravel 9 now uses withSymfonyMessage instead of withSwiftMessage. https://laravel.com/docs/9.x/upgrade – Svenn Richard Mathisen Feb 13 '23 at 17:23
0

You can do this by adding an X-SMTPAPI header that contains the categories, but Laravel doesn't expose custom headers so you have to drop down to SwiftMailer directly. For an example, take a look at this thread

Community
  • 1
  • 1
bwest
  • 9,182
  • 3
  • 28
  • 58