vanilla php 将 base64 转换为电子邮件附件中的图像

vanilla php convert base64 to image in email attachment

我有一个 php 脚本可以给我发送电子邮件。在此电子邮件数据中,我发送了 base64 图像数据,但我想要的是将 base64 转换为 jpeg,然后通过电子邮件将其添加为附件。

<?php
header('Access-Control-Allow-Origin: *');

if(isset($_POST['email'])){
    $to      = 'my@email.com';
    $subject = "New submission from ".$_POST['email'];
    $message = $_POST['message'];
    $image = base64_to_jpeg( $_POST['image'], 'image.jpeg' ); //this is base64 image
    $subscribe = $_POST['subscribe'];
    $headers = "From: ".$_POST['email']." <".">\r\n"; $headers = "Reply-To: ".$_POST['email']."\r\n";
    $headers = "Content-type: text/html; charset=iso-8859-1\r\n";
    'X-Mailer: PHP/' . phpversion();
    if(mail($to, $subject, $image, $headers)) echo json_encode(['success'=>true]);
    else echo json_encode(['success'=>false]);
    exit;
 }

function base64_to_jpeg($base64_string, $output_file) {
    // open the output file for writing
    $ifp = fopen( $output_file, 'wb' );

    // split the string on commas
    // $data[ 0 ] == "data:image/png;base64"
    // $data[ 1 ] == <actual base64 string>
    $data = explode( ',', $base64_string );

    // we could add validation here with ensuring count( $data ) > 1
    fwrite( $ifp, base64_decode( $data[ 1 ] ) );

    // clean up the file resource
    fclose( $ifp );

    return $output_file;
}
?>

$imagedata:image/png;base64,iVBORw0KGg

我遇到的问题是,在发送电子邮件时,电子邮件仅包含纯文本“image.jpeg”,而不是显示图像或附加图像...

知道如何解决这个问题吗?

谢谢。

$image 传递到邮件正文显然会发送名称,因为这就是您从函数返回的内容。

但是如果你用图像标签传递它;

mail($to, $subject, '<img src="' . $image . '" alt="'. $image . '">', $headers); // I used PHP template strings to create the img tag

您肯定会得到传递到邮件正文中的数据字符串

这是你发给我的 link 的截图

这是我的完整代码 运行 base64_to_jpeg 是我从问题中得到的函数

<?php

function base64_to_jpeg($base64_string, $output_file)
{
    // open the output file for writing
    $ifp = fopen($output_file, 'wb');

    // split the string on commas
    // $data[ 0 ] == "data:image/png;base64"
    // $data[ 1 ] == <actual base64 string>
    $data = explode(',', $base64_string);

    // we could add validation here with ensuring count( $data ) > 1
    fwrite($ifp, base64_decode($data[1]));

    // clean up the file resource
    fclose($ifp);

    return $output_file;
}

    $image = base64_to_jpeg(base64_string_from_link, 'image.jpeg')
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Base 64</title>
</head>
<body>
    <?php echo '<img src="' . $image . '" alt="' . $image . '">'; ?>
</body>
</html>

我现在明白你的问题了,当你将 $image 传递给邮件正文时,显示 alt 文本只是因为邮件不知道从哪里下载图像。

当您通过邮件发送图片时,图片 link 必须是绝对路径,这样邮件才能知道从哪里下载图片。

因此,要么将该图像上传到您的网站文件管理器并使用像这样的绝对路径,<img src="https://picsum.photos/id/237/200/300">

不要将图像转换为 .jpeg,只需将 base 64 字符串作为图像的 src <img src="data:image/png;base64,iVBORw0KGg">

我还在您的代码中看到您没有将 $headers 连接在一起,而只是重置值。 (即您使用 = 而不是 .=