How To Pass Mailgun ID create in MailgunTransport to an Event Listener, in Laravel?

…衆ロ難τιáo~ 提交于 2020-01-05 07:15:20

问题


In my Laravel application, I have an Event Listener that triggers when someone is added to a course, then emails that user "You've been added to course".

I am using Mailgun to send these emails, and in this Listener, I call \Mail which builds a blade file and sends the email to the users, which all works fine.

My issue is I want to store that Mailgun ID. Which in Laravel v6 gets added in Illuminate\Mail\Transport\MailgunTransport@send and I can access that ID by calling $message->getId() which I think can be found in vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php

How do I return $message->getId() so I can use it in my Listener?

In my Listener \Mail I call my Model to create the newly sent email record and I want to be able to store that ID.

Below is a link to my initial question which https://stackoverflow.com/users/2343305/ilgala was able to help out:

How retrieve Mailgun Delivered Message in Laravel


回答1:


I've answered also to your old question. I think you're missunderstanding the process. I'll create a complete example down here for Laravel 6.x but it should be the same for the older versions.

1. Configure mailgun

That's the easy part. Just change the services.php file with the mailgun credentials and remember to require with composer the guzzlehttp/guzzle package, otherwise you won't be able to send e-mails. Then change the .env file and set the MAIL_DRIVER to mailgun. In this way Laravel will know that it has to use that driver to send e-mails.

2. Create your logic

Let's say you have to send an e-mail each time a customer creates and order. You will have an OrderController somewhere in your codebase with a store method that creates the order and send the email right after. Something like

public function store(Request $request)
{
  // Validate your request
  $this->validate([...]);

  // Create the order
  $order = new Order();
  $order->fill($request->only([...]));

  // Save order
  $order->save();

  // Send confirmation email;
  Mail::to(auth()->user())->send(new OrderCreated($order));
}

Since you setted the mailgun Driver, the Mail facade will automatically use the MailgunTransport class.

3. Create the listener

As explained in my other answer, set the listener in the EventServiceProvider. Than, once you created the listener you can retrieve the Mailgun ID as follows:

/**
 * Handle the event.
 *
 * @param  \Illuminate\Mail\Events\MessageSent  $event
 * @return void
 */
public function handle(MessageSent $event)
{
    // Retrieve mailgun ID from the message headers
    $id = $event->message->getHeaders()->get('X-Mailgun-Message-ID');
}


来源:https://stackoverflow.com/questions/59290352/how-to-pass-mailgun-id-create-in-mailguntransport-to-an-event-listener-in-larav

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!