使用 Laravel 的 Mailgun driver,您如何(优雅地)通过电子邮件发送自定义数据和标签?

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

所以我正在使用 Laravel 5.1 并尝试与 Mailgun 集成。好吧,这很简单,但现在我正尝试从我的应用程序发送 custom variables 以及我的电子邮件。

我实际上正在从 Mandrill 切换我们的应用程序,因为它们 "new direction" 等等。有了它们,我可以通过电子邮件 headers 提供变量和标签,但是对于 Mailgun,这仅在您通过 SMTP 发送时有效。在 Laravel 中,Mail::send() 使用 API 调用,所以理论上我会用 "v:my-custom-data" => "{"this_id": 123}" 添加元数据,但我想避免改变核心 类 那样。

我也考虑过使用Bogardo/Mailgun,但是我必须将所有Mail::send()替换为Mailgun::send(),然后我无法在本地发送电子邮件(基于环境电子邮件 driver),然后申请将 "married" 发送到 Mailgun。

有人做过吗?如果我在这里不清楚,请告诉我。

我解决了自己的问题。我错了,您可以 通过 SMTP 方法添加自定义变量:

// 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');
    });

我的测试不够充分。很高兴知道,但我认为这是一个未记录的功能,所以我建议谨慎使用。

您可以在 Laravel 5 中这样做:

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

Laravel 5.4+

更新

正如您在 offical docs 中看到的那样:

Mailable 基础 class 的 withSwiftMessage 方法允许您注册一个回调,该回调将在发送消息之前用原始 SwiftMailer 消息实例调用。这使您有机会在发送之前自定义消息:

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

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

Laravel Mailgun 驱动程序的实现不支持 options/parameters。

这是一个要点,它增加了对本机驱动程序的支持:https://gist.github.com/j0um/27df29e165a1c1e0634a8dee2122db99