【问题标题】:Send image as attachment as well as inline using Sendgrid API使用 Sendgrid API 将图像作为附件和内联发送
【发布时间】:2021-07-06 08:30:48
【问题描述】:

我想发送一封带有图片作为附件的电子邮件,并将其嵌入正文中。

<?php
$email = "to@example.com";
$name = "some_name";
$img = file_get_contents('image.jpg');
$body = '<img src = "cid:image">';
$subject = "Test email";

      

$headers = array(
    'Authorization: Bearer API_KEY',
    'Content-Type: application/json'
);

$data = array(
    "personalizations" => array(
        array(
            "to" => array(
                array(
                    "email" => $email,
                    "name" => $name
                )
            )
        )
    ),
    "from" => array(
        "email" => "from@example.com"
    ),
    "subject" => $subject,
    "content" => array(
        array(
            "type" => "text/html",
            "value" => $body
        )
    ),

    "attachments" => array(
        array(
            "content" => base64_encode($img),
            "type" => "image/jpeg",
            "filename" => "image",
            "disposition" => "inline",
            "content_ID" => "image",
            //"disposition" => "attachment"
        )
    )         
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.sendgrid.com/v3/mail/send");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);

echo $response;?>

问题是它要么作为内联内容要么作为附件,但不是两者兼而有之。我不知道如何解决这个问题。 我尝试为内联和附件添加两个单独的 attachments 块,但它总是考虑第二个块。 似乎没有任何效果。

【问题讨论】:

    标签: php image api curl sendgrid


    【解决方案1】:

    这里是 Twilio SendGrid 开发人员宣传员。

    您不想在 array 中设置两个相同的键(就像为 disposition 所做的那样)或设置两个 attachments 块。相反,您应该将两个项目添加到 attachments 块中,如下所示:

        "attachments" => array(
            array(
                "content" => base64_encode($img),
                "type" => "image/jpeg",
                "filename" => "image-inline",
                "disposition" => "inline",
                "content_ID" => "image-inline",
            ),
            array(
                "content" => base64_encode($img),
                "type" => "image/jpeg",
                "filename" => "image-attachment",
                "disposition" => "attachment",
                "content_ID" => "image-attachment",
            ),
        ) 
    

    请注意,我还为内联文件和附加文件提供了不同的文件名和内容 ID。

    【讨论】:

    • 我不能使用不同的文件名,因为文件会每隔一段时间自动从网站下载同名文件。换句话说,会自动下载不同的文件,并且每次将之前的图像替换为新图像。
    • 但是你可以给那个文件名加上前缀或后缀,对吧?
    • 你能告诉我怎么做吗?我可能会问一个愚蠢的问题,但我是新手,我不知道该怎么做。
    • 查看您的代码,我认为这实际上并不重要。您可以像我在上面的代码中那样调用文件名“image-inline”或“image-attachment”,对吧?你试过这样运行它吗?
    猜你喜欢
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多