我是sendgrid的新手,想将sendgrid与Laravel集成。在这里我尝试了 - 在应用程序\邮件\发送网格电子邮件中添加了以下代码.php
namespace AppMail;
use IlluminateBusQueueable;
use IlluminateMailMailable;
use IlluminateQueueSerializesModels;
use IlluminateContractsQueueShouldQueue;
class SendgridEmail extends Mailable
{
use Queueable, SerializesModels;
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function build()
{
$address = 'demotest@gmail.com';
$subject = 'This is a demo!';
$name = 'Sam';
return $this->view('emails.templateUserRegister')
->from($address, $name)
->subject($subject)
->with([ 'message' => $this->data['message'] ]);
}
}
- 创建了模板文件视图/电子邮件/模板用户注册.刀片.php作为
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
</head>
<body>
<h2>Bowoot Email</h2>
<p>{{ $message }}</p>
</body>
</html>
- 将以下代码添加到控制器
use AppMailSendgridEmail; // on top of class
public function sendemail()
{
$data = array('message' => 'This is a SendgridEmail test!');
Mail::to('user@gmail.com')->send(new SendgridEmail($data));
}
当我运行代码时,我发现错误消息如下
(2/2( 错误异常 htmlspecialchars(( 期望参数 1 为字符串,对象给定 (查看: C:\xampp\htdocs\bowoot\resources\views\email\templateUserRegister.blade.php( 在助手中.php(第 547 行(
我无法理解问题是什么。请帮忙。
如果提供的信息准确,则返回视图emails.templateUserRegister
,它应该是email.templateUserRegister
的。(注意 s( 我之所以这样说,是因为这是你的视图路径。
views/email/templateUserRegister.blade.php
而且它绝对没有"s"。
编辑
而不是这样做:
return $this->view('emails.templateUserRegister')
->from($address, $name)
->subject($subject)
->with([ 'message' => $this->data['message'] ]);
试试这个:
$message = $this->data['message'];
return $this->view('emails.templateUserRegister')
->from($address, $name)
->subject($subject)
->with('message', $message);
并让$data
app\Mail\SendgridEmail.php
private
或protected
.
如果这不起作用,请尝试从控制器以字符串而不是数组的形式发送$data
。其余代码将保持不变,此行将更改:
->with([ 'message' => $this->data['message'] ]);
自:
->with('message', $this->data);
而且您仍然需要将$data
的访问权限更改为private
或protected
.
编辑 2
如果你检查Laravel的邮件文档,它是这样说的:
注意:$message变量始终传递到电子邮件视图,并允许 附件的内联嵌入。因此,最好避免通过 视图有效负载中的消息变量。
因此,要解决此问题,只需将$message
更改为其他名称,例如$data
或$text
.更改此设置:
->with([ 'message' => $this->data['message'] ]);
对此:
->with( 'text', $this->data['message'] );
我希望这可以解决问题。