【问题标题】:How can i pass the variables in the Mail body with laravel?如何使用 laravel 传递邮件正文中的变量?
【发布时间】:2021-10-30 14:55:28
【问题描述】:

我想在我的邮件正文中传递变量,我该怎么做。

我在做。

我想发送来自数据库的邮件模板,在该模板中,我已经定义了发送时要替换的变量。

`$record = DB::table('email_templates')->select('content','em_temp_id')->where('em_temp_id', 
           $request->select_temp)->where('is_active', 1)->first();
           $body = htmlspecialchars_decode($record->content);' //the html body

还有我的邮件功能

'Mail::send([],[], function($message) use ($Toarray, $ToCCarray, $ToBCCarray, $subject, $body, 
       $is_plainOrHtml){
       $message->to($Toarray, '');
       $message->cc($ToCCarray, '');
       $message->bcc($ToBCCarray, '');
       $message->subject($subject);
       $message->setBody($body, 'text/html'); //for plain text email
 });'

数据库中的模板如下:

`<p>Dear {{$userName}},</p>
 <p>The {{$service_provider}}, requesting you to join <strong>{{$channel}}</strong> service. 
 </p>`

要传递的数组:

`$arr_pass['userName'] = 'John';
 $arr_pass['service_provider'] = 'abc.com';
 $arr_pass['channel'] = 'Tom';`

如何在邮件正文中传递这个数组?

【问题讨论】:

标签: laravel


【解决方案1】:

您可以通过扩展 Mailable 类来创建一个新的 Mail 类,并将您的数组传递给 Mail 类的构造函数。 在下面的示例中,RFIRequestMail 是在 App\Mail 目录中创建的 Mail 类。

RFIRequestMail.php

 <?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class RFIRequestMail extends Mailable
{
    use Queueable, SerializesModels;

    public $verifierData;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('mail-view-template');
    }
}

邮件控制器

$sendData = User::find($id);
$data = User::find($company_id);
$sendData["link"] = env("APP_URL");
$sendData["year"] = $request->get("year");
$sendData["user"] = $data->first_name.' '.$data->last_name;
Mail::to($data->email)->send(new RFIRequestMail($sendData));

【讨论】:

  • 不,我没有视图文件。正如我所说,我的电子邮件模板来自 DB。
【解决方案2】:

您可以使用Blade::compileString,它将翻译您从数据库中读取的刀片模板。这样做有一个棘手的部分 - 如何发送变量的数据。

这里有一些提示:

  1. 你可以使用这个库:https://github.com/TerrePorter/StringBladeCompiler
  2. 您可以使用类似于Is there any way to compile a blade template from a string?BladeCompiler
  3. 通过检查https://laravel.com/api/8.x/Illuminate/View/Compilers/BladeCompiler.html 的实现来滚动您自己的编译器

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-16
    • 2018-06-18
    • 2017-11-11
    • 2016-07-18
    • 2020-07-27
    • 2017-06-30
    • 1970-01-01
    • 2011-06-10
    相关资源
    最近更新 更多