提问人:anbu 提问时间:10/15/2023 最后编辑:anbu 更新时间:10/16/2023 访问量:58
在 Laravel 中使用准备好的模板发送电子邮件时遇到麻烦:
Trouble Sending Emails with Prepared Templates in Laravel:
问:
我遇到了错误和问题,尤其是在处理异常和转义 HTML 字符时。我将不胜感激任何有关使用 laravel 10 发送带有模板的电子邮件的最佳实践的指导,以及解决我面临的问题的任何见解。先谢谢你!
在邮件中,只有html代码是可见的,预期是html页面。
我正在使用 [][1]https://app.bootstrapemail.com/templates/free-simple-card
public function prepareTemplate($subject, $body, $templateId)
{
$subject = htmlentities($subject, ENT_QUOTES, 'UTF-8');
$body = htmlentities($body, ENT_QUOTES, 'UTF-8');
// Load the template from your database or source
$template = $this->templates::where('InternalID', $templateId)->first(); // Assuming you want to retrieve a single template.
$templateHeader = $template->Header;
$templateFooter = $template->Footer;
// Replace placeholders in the template body with dynamic content
$templateBody = str_replace('{{ subject }}', $subject, $template->Body);
$templateBody = str_replace('{{ body }}', $body, $templateBody);
// Escape HTML characters in subject and body
// Combine the header, dynamic body, and footer
$completeTemplate = $templateHeader . $templateBody . $templateFooter;
return $completeTemplate;
}
// SendMail
public function SendMail($notification)
{
// Inject the Templates model when creating TemplateService
$templateService = new TemplateService(new Templates);
$template = $templateService->prepareTemplate($notification->Subject,$notification->Body,1);
try {
Mail::to($notification->Contact)->send(new MyTestEmail($notification,$template));
} catch (\Exception $e) {
$this->updateNotificationService->UpdateTriedCount($notification);
Log::info(['Failed Notification '=>$notification]);
return false;
}
}
我正在使用此模板 https://app.bootstrapemail.com/templates/free-simple-card
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/dBZAi.png
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class MyTestEmail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*/
private $notification;
private $template;
public function __construct($notification ,$template)
{
$this->notification = $notification;
$this->template = $template;
}
/**
* Get the message envelope.
*/
public function envelope(): Envelope
{
return new Envelope(
subject: $this->notification->Subject,
);
}
/**
* Get the message content definition.
*/
public function content(): Content
{
return new Content(
html: 'mail.test-email',
with: [
'template'=>$this->template
]
);
}
/**
* Get the attachments for the message.
*
* @return array<int, \Illuminate\Mail\Mailables\Attachment>
*/
public function attachments(): array
{
return [];
}
}
答:
0赞
anbu
10/16/2023
#1
- php artisan vendor:publish --tag=laravel-mail 2.in test.email.blade 页面更新为 {!! $template !!}
在此 2 个步骤之后,问题得到解决并按预期工作。
评论
MyTestEmail
mail.test-email