【问题标题】:Laravel - Mail::send() How to pass data (in array format) to email html and send itLaravel - Mail::send() 如何将数据(以数组格式)传递到电子邮件 html 并发送
【发布时间】:2019-08-27 15:50:37
【问题描述】:

我正在尝试在发送之前将请求中的值(存储为数组)传递给 html 格式的电子邮件。

$data = array('email' => $request->get('email'), 'name' => $request->get('name'));
    Mail::send('emails.email', ['data' => $data], function ($message) use ($data) {
        $message->subject('Hello world!');
        $message->to($data['email'], $data['name']);
    });

这是我在 email.blade.php

中的电子邮件 html 格式文件
<h2>HELLO YOU HAVE A NEW EVENT!</h2>
<h3>TO {{$name}}</h3>
<h4>See more details .... <a href="http://localhost:8000/event" target="_blank">Events</a></h4>

但似乎html文件没有收到发送的变量($name)

如何将数据(数组格式)传递给电子邮件html?

我尝试在没有 $ name 变量的情况下发送。看来没有问题。一切都很顺利但是我真的需要使用变量请帮助我

如果使用此代码,我可以使用 $name

$data['name'] = "Guest";
    Mail::send('emails.email', $data, function ($message) {
        $message->to('email@gmail.com', 'name')
                ->subject('topic');
    });

为什么?

【问题讨论】:

  • 在邮件类中应该构建方法,在构建方法中返回 $this->view() 可能对你有帮助
  • laravel.com/docs/5.8/mail#view-data 通过with 方法可能是您正在寻找的东西

标签: php laravel html-email sendmail


【解决方案1】:
Mail::send('emails.email', ['data' => $data], function ($message) use ($data) {
        $message->subject('Hello world!');
        $message->to($data['email'], $data['name']);
});

您传递的是 data 变量,而不是 name (['data' =&gt; $data])。所以从该数组中获取名称:

<h2>HELLO YOU HAVE A NEW EVENT!</h2>
<h3>TO {{ $data['name'] }}</h3>

或直接传递$data 变量,以便您可以将其所有值作为单独的变量访问:

Mail::send('emails.email', $data, function ($message) use ($data) {
        $message->subject('Hello world!');
        $message->to($data['email'], $data['name']);
});

【讨论】:

    【解决方案2】:

    首先你必须像这样在你的邮件类中声明变量:

    <?php
    
    namespace App\Mail;
    
    use Illuminate\Bus\Queueable;
    use Illuminate\Mail\Mailable;
    use Illuminate\Queue\SerializesModels;
    use Illuminate\Contracts\Queue\ShouldQueue;
    
    class MailForm extends Mailable
    {
        use Queueable, SerializesModels;
        public $fullname;
        /**
         * Create a new message instance.
         *
         * @return void
         */
        public function __construct($fullname)
        {
            //
            $this->fullname     = $fullname;
    
        }
    
        /**
         * Build the message.
         *
         * @return $this
         */
        public function build()
        {
            return $this->view('sendmail');
        }
    }
    

    那么在您看来,您现在可以调用该变量

    {{ $fullname }}
    

    不要忘记在你的控制器中调用邮件类和邮件门面:

    use App\Mail\MailForm;
    use Illuminate\Support\Facades\Mail;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-09
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 2014-06-22
      相关资源
      最近更新 更多