Reputation: 868
In my Node.js application, I followed the Mailgun docs https://documentation.mailgun.com/en/latest/quickstart-sending.html#send-with-smtp-or-api for sending an email similar to the following:
mailgun.messages().send(data, (error, body) => {
console.log(body);
// body is {id: some_mailgun_built_id, message: 'Queued. Thank You'}
// which I store the body.id in my database
});
The issue I am faced with is how can I access that same Mailgun response when I send an email with Laravel? The Mailgun docs don't provide any examples showing how to retrieve that data.
This is how I am sending emails with Laravel:
\Mail::to($recipients)->send(
// this just renders my blade file which formats my email
new SendEmail($email);
);
// ?? How to get Message was sent object here
If anyone knows of any solution it would be greatly appreciated!
Upvotes: 2
Views: 2963
Reputation: 3419
Hello and Welcome to SO!
Laravel has two events for the emails as explained in the official documentation: MessageSending
and MessageSent
You can follow the events official documentation in order to listen for these specific events:
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'Illuminate\Mail\Events\MessageSending' => [
'My\Email\Listener',
],
'Illuminate\Mail\Events\MessageSent' => [
'My\Other\Listener',
],
];
You will receive as input the Swift_message
which contains a header that is the Mailgun ID you're looking for. Let's have a look at the MailgunTransport@send
source code in order to understand what's going on behind the scenes:
/**
* {@inheritdoc}
*/
public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null)
{
// [...]
$response = $this->client->request(
'POST',
"https://{$this->endpoint}/v3/{$this->domain}/messages.mime",
$this->payload($message, $to)
);
$message->getHeaders()->addTextHeader(
'X-Mailgun-Message-ID', $this->getMessageId($response) // <-- HERE LARAVEL SETS THE MESSAGE ID
);
// [...]
}
Looking for the same key in your listener you can recover the message ID that mailgun assigned to your e-mail. Unfortunately you can't access the entire Mailgun response but with the API you can easily retrieve your message.
Upvotes: 2