如何在 Laravel 5.1 中为电子邮件添加标题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32338842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:17:00  来源:igfitidea点击:

How to add headers to email in Laravel 5.1

phplaravellaravel-5

提问by geoffs3310

Is there a way to add default headers to all emails in Laravel 5.1? I want all emails to be sent with the following header:

有没有办法在 Laravel 5.1 中为所有电子邮件添加默认标题?我希望所有电子邮件都带有以下标题:

x-mailgun-native-send: true

回答by Maxim Lanin

Laravel uses SwiftMailer for mail sending.

Laravel 使用 SwiftMailer 发送邮件。

When you use Mail facade to send an email, you call send() method and define a callback:

当您使用 Mail facade 发送电子邮件时,您调用 send() 方法并定义一个回调:

\Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
    $m->to($user->email, $user->name)->subject('Your Reminder!');
});

Callback receives $mvariable that is an \Illuminate\Mail\Messageobject, that has getSwiftMessage()method that returns \Swift_Messageobject which you can use to set headers:

回调接收$m作为\Illuminate\Mail\Message对象的变量,该变量具有getSwiftMessage()返回\Swift_Message可用于设置标头的对象的方法:

$swiftMessage = $m->getSwiftMessage();

$headers = $swiftMessage->getHeaders();
$headers->addTextHeader('x-mailgun-native-send', 'true');

回答by Gayan

Slight modification to @maxim-lanin's answer. You can use it like this, fluently.

对@maxim-lanin 的回答略有修改。你可以像这样流畅地使用它。

\Mail::send('email.view', ['user' => $user], function ($message) use ($user) {
    $message->to($user->email, $user->name)
        ->subject('your message')
        ->getSwiftMessage()
        ->getHeaders()
        ->addTextHeader('x-mailgun-native-send', 'true');
});