php - Laravel:API 上的动态电子邮件内容
问题描述
我正在 Laravel 上构建一个电子邮件 API。我想通过这个 API 在我的其他项目上发送电子邮件。我通过此 API 成功发送电子邮件。但是,电子邮件内容在客户端是硬编码的。例如:
$body = "Dear $user->name,<br />
Thank you for your order.";
$client->request('POST', 'http://api.test/send_mail?token=' . $token, ['form_params' => [
'from' => 'client@test.com',
'title' => 'API Test Mail',
'to' => 'customer@test.com',
'body' => $body,
'signature' => 'Regards'
]]);
我的目标尤其是在email body
没有硬编码的情况下创建动态。因此,我将电子邮件内容保存到数据库中。我的计划是通过客户端的请求触发保存的电子邮件内容。在对具有类似结构的电子邮件系统进行了一些研究之后,我认为,我必须将相关内容保存到数据库中,如下所示:
亲爱的{{用户名}}
谢谢您的订单。
通过这种方式,我只会将username
信息从客户端发送到 API。我不必处理 HTML 电子邮件内容。
但是,我不确定在此阶段之后该做什么。如何$username
从客户端向 API 发送和解析信息?我是否必须在每个参数上向 API 添加请求?这是我当前的请求规则:
return [
'title' => 'required',
'from' => 'required|email',
'to' => 'required|email',
'body' => 'required',
'signature' => 'nullable',
'email_template' => 'nullable'
];
这也是我的邮件降价:
@component('mail::message')
{!! $mail['body'] !!}
@if(array_key_exists('signature', $mail))
<p>{!! $mail['signature'] !!}</p>
@endif
@endcomponent
实际上,动态参数将是body
. 如果我想将$username
动态变量添加到电子邮件正文中,是否应该将其添加到请求规则以及邮件降价中?如果是这样,我必须对每个保存的不同电子邮件内容及其不同参数进行一些静态事务。
如何以更清晰的方式构建此结构?
解决方案
是的,您应该将每个参数解析到您的 API。你可以这样做:
$data['username'] = 'John';
$data['other'] = 'other';
$client->request('POST', 'http://api.test/send_mail?token=' . $token,
['form_params' =>
[
'from' => 'client@test.com',
'title' => 'API Test Mail',
'to' => 'customer@test.com',
'data' => $data,
'signature' => 'Regards',
'template_id' => 'template_id' // parse if you have multi templates
]]);
您可以在 API 控制器中发送这样的电子邮件。
public function sendEmail(Request $request)
{
$template = Template::findorfail($request->template_id);
$body = $template->body;// this is template dynamic body. You may get other parameters too from database. $title = $template->title; $from = $template->from;
foreach($request->data as $key=>$parameter)
{
$body = str_replace('{{'.$key.'}}', $parameter, $body); // this will replace {{username}} with $data['username']
}
$request->body = $body;
$mailObject = new MyMail($request); // you can make php artisan make:mail MyMail
Mail::to($request->to)->send($mailObject);
}
...
class MyMail extends Mailable
{
use Queueable, SerializesModels;
public $request;
public function __construct($request)
{
$this->request= $request;
}
public function build()
{
return $this->subject($this->request['title'])
->from($this->request['from'])
->markdown('components.mail.myTemplate');
}
}
然后在myTemplate.blade.php
你可以渲染{!!$request['body'] !}}
希望这对您有所帮助。
推荐阅读
- php - PHP Parse 错误:语法错误,意外的 'else' (T_ELSE) 尽管所有括号都存在于代码中
- api - Testcafe - 从请求有效负载中检索数据
- r - 加载包“ape”和“Rcpp”时出现R错误
- .htaccess - 在受密码保护的网站上的 Safari 上显示书签图标
- python-3.x - 使用 nsepy 获取大部分股票的空数据框
- flutter - razorpay_flutter 在 PUBSPEC.YML 文件中集成它显示错误
- php - 如何在laravel中使用url传递`?`?
- javascript - 使用 ES6 类扩展内置数组 - 方法不是函数错误
- python - 如何使用 python API 列出所有数据流作业
- kubernetes - 将已部署 pod 的数量从部署/复制集/有状态传递到 kubernetes 中的那些 pod