Using Laravel's Mailgun driver, how do you (gracefully) send custom data and tags with your email?

大憨熊 提交于 2019-12-03 10:58:38

I fixed my own problem. I was wrong, YOU CAN add custom variables via the SMTP method:

// Send email with custom variables and tags in Laravel
Mail::send('emails.blank',
    ['html' => 'This is a test of Mailgun. <strong>How did it work out?</strong>'],
    function($message) {
        $message->to('jack@mailinator.com');
        $message->subject('Mailgun API Test');

        $headers = $message->getHeaders();
        $headers->addTextHeader('X-Mailgun-Variables', '{"msg_id": "666", "my_campaign_id": 1313}');
        $headers->addTextHeader('X-Mailgun-Tag', 'test-tag');
    });

My testing was just inadequate. Very good to know, however I think this is an undocumented feature, so I suggest using with caution.

You can just do like this in Laravel 5 :

Mail::send(['text' => 'my_template'], $data, function ($message) {
  ..
  $message->getSwiftMessage()->getHeaders()->addTextHeader('X-Mailgun-Tag', 'my-tag');
});

Update for Laravel 5.4+

As you can read in the offical docs:

The withSwiftMessage method of the Mailable base class allows you to register a callback which will be invoked with the raw SwiftMailer message instance before sending the message. This gives you an opportunity to customize the message before it is delivered:

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    $this->view('emails.orders.shipped');

    $this->withSwiftMessage(function ($message) {
        $message->getHeaders()
                ->addTextHeader('Custom-Header', 'HeaderValue');
    });
}

Laravel implementation of the Mailgun Driver doesn't support options/parameters.

Here's a Gist which adds support to the native driver : https://gist.github.com/j0um/27df29e165a1c1e0634a8dee2122db99

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