我正在使用 laravel,下面是我遵循的步骤,
我正在使用编辑器向用户发送电子邮件,
来自编辑器,我已上传图片,
该图像以base64格式上传
我正在通过电子邮件将该编辑器内容发送给用户
我已检查 base64 字符串是否正确并向我显示图像 也可以用我的系统显示该图像
但是当我要通过电子邮件发送该图像时,
该图像对我来说不可见。
我检查了图像 src 属性,显示类似 -
<img style="width:224px">
在 gmail 中,这里 src 属性被删除,但我在发送电子邮件之前检查了该标签,有 src 标签带有正确的 base64 编码字符串
请帮我在电子邮件中显示图像,
要发送邮件,我使用 Laravel 自己的电子邮件配置,如下所示,
use App\Events\SendMail;
$mailData['toName'] = $toUserFullname;
$mailData['toEmail'] = $toEmail;
$mailData['fromName'] = $fromName;
$mailData['fromEmail'] = $fromEmail;
$mailData['emailSubject'] = $templateData['email_subject'];
$mailData['emailContent'] = $templateData['email_body'];
\Event::fire(new SendMail($mailData));
电子邮件中不太支持 Base64 编码的图像。大多数网络电子邮件客户端(包括 Gmail)不支持它们,并且在 Outlook 中被完全阻止。
所以我想到的第一个解决方案是在发送电子邮件之前从 Base64 字符串创建实际的图像文件。像这样的帮助:
$filename_path = md5(time().uniqid()).".jpg";
$decoded=base64_decode($base64_string_img);
file_put_contents("path/to/save/image/".$filename_path,$decoded);
您也不应该忘记取消链接这些图像,以防以后不再需要它们。
您还可以尝试使用内联附件。
<img src="{{ $message->embedData($data, $name) }}">
这里是一个自定义代码,您可以在 Laravel 中使用此代码,如果您发送 HTML,图像标签具有 Base64 将转换为服务器图像路径
preg_match_all('/]+src="data:image/[^;]+;base64,[^"]+"[^>]*>/i', $data['html'], $matches) ;
foreach ($matches[0] as $imgTag) {
preg_match('/src="(data:image\/[^;]+;base64,[^"]+)"/', $imgTag, $srcMatch);
if (isset($srcMatch[1])) {
// Use a different variable name to avoid overwriting $data
list(, $base64Data) = explode(',', $srcMatch[1]);
$imageData = base64_decode($base64Data);
// Create a temporary file to store the image
$tempFilePath = tempnam(sys_get_temp_dir(), 'upload') . '.jpg';
file_put_contents($tempFilePath, $imageData);
// Upload the image to S3
$filePath = $this->uploadOne(new UploadedFile($tempFilePath, 'image.jpg'), 'images', null, 's3'); // Specify your S3 disk
// Get the URL of the uploaded image
$s3Url = Storage::disk('s3')->url($filePath);
// Replace the Base64 src with the S3 URL in the HTML
$data['html'] = str_replace($srcMatch[0], 'src="' . $s3Url . '"', $data['html']);
// Delete the temporary file
unlink($tempFilePath);
}
}