Laravel覆盖邮件以自动添加纯文本版本
我正在对我的Laravel应用程序进行一些更改,以便自动将纯文本版本添加到我的电子邮件中。。我用图书馆来做这件事 我会通过运行Laravel覆盖邮件以自动添加纯文本版本,laravel,laravel-5.3,Laravel,Laravel 5.3,我正在对我的Laravel应用程序进行一些更改,以便自动将纯文本版本添加到我的电子邮件中。。我用图书馆来做这件事 我会通过运行 \Html2Text\Html2Text::convert($content) 现在我想重写laravels Mailable.php buildView()函数来自动生成文本。我的问题是:如何正确地覆盖它?我在哪里可以重新声明它?邮件程序是由邮件程序服务提供商定义的,您可以在配置/app.php下的'providers'中看到它的注册,您将看到: \Illumin
\Html2Text\Html2Text::convert($content)
现在我想重写laravels Mailable.php buildView()函数来自动生成文本。我的问题是:如何正确地覆盖它?我在哪里可以重新声明它?邮件程序是由邮件程序服务提供商定义的,您可以在
配置/app.php
下的'providers'
中看到它的注册,您将看到:
\Illuminate\Mail\MailServiceProvider::class,
因此,您所需要做的就是删除MailServiceProvider注册,并根据您的更改创建您自己的提供商,然后注册您自己的提供商
确保您执行了illumb\Contracts\Mail\Mailer
合同
但是你不需要强>
Laravel附带的邮件程序已经支持发送HTML和普通版本的电子邮件
Mailer::send()
方法的第一个参数是@param string | array$view
,您通常在这里发送电子邮件HTML版本的视图名称,但是,您可以改为发送如下数组
Mailer::send([
'html' => 'my-mails.notification-in-html',
'text' => 'my-mails.notification-in-text',
], $data, $callback);
你甚至可以定义一个不同的文本,删除你不会放在纯文本版本中的东西,或者调整一个在纯文本上看起来不错的不同签名,也可以设置不同的格式
有关更多信息,您可以查看illighted\Mail\Mailer
类中的parseView()
因此,您有两个选择:
- 创建您自己的邮件程序并注册它,而不是默认的邮件程序
- 或者只需使用一组视图调用邮件程序
<?php
namespace App\Mail;
// [...] some other imports
use Illuminate\Mail\Mailable;
class BaseMailable extends Mailable
{
// [...] some other code
/**
* Method to add plain text version by converting it from HTML version
* Separate plain text view could be used if exists
*/
public function viewHtmlWithPlainText($view, array $data = [])
{
// NOTE: we render HTML separately because HTML and Plain versions have the same data
// and we need to pass `plain` parameter to the HTML template to render it differently
$this->html( view($view, $this->buildViewData())->render() );
$plainTextView = str_replace('emails.', 'emails.txt.', $view);
$plainTextAttrs = [
'plain' => true,
'senderName' => config('app.name')
];
if (view()->exists($plainTextView)) {
$this->text( $plainTextView, array_merge($plainTextAttrs, $data) );
} else {
$this->text( $view, array_merge($plainTextAttrs, $data) );
}
return $this;
}
}
在模板中,您将为纯文本电子邮件提供$plain=true
变量,这样您就可以在
@if (empty($plain))
<div>Some HTML content</div>
@else
Some plain text content
@endif
@if(空($plain))
一些HTML内容
@否则
一些纯文本内容
@恩迪夫
@if (empty($plain))
<div>Some HTML content</div>
@else
Some plain text content
@endif