mailgun发送内嵌图像不工作?

2024-06-09 18:02:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我用邮筒发邮件。 我尝试使用pythonapi

pwd = "path-to-image/logo.png"
return requests.post(
     "https://api.mailgun.net/v2/sandboxsomething.mailgun.org/messages",
     auth=("api", "key-something"),
     files=[("inline", open(pwd)),],
     data={"from": src,
           "to": des,
           "subject": sub,
           "html": message})

但它不能发送图像。在

之后,当我打印print open(pwd).read()时,我尝试只显示png文件,得到:

^{pr2}$

但是当我尝试print open('path-to-image/a.txt')时,我得到了文件的内容:

all content of a.text
none

为什么png文件没有被读取?在


Tags: 文件topathimageapipythonapireturnpng
3条回答
open(pwd,"rb")

您可以使用此链接:https://stackoverflow.com/a/23566951/3726821

图像打开必须:

open(pwd,"rb")

以二进制模式读取。在

回答这个有点晚了,但我也在寻找一个解决方案,在网上找不到。我自己编了代码,教我在这里分享。在

当mailgun向端点发布新消息时,它将内联图像解析为附件。这里有一个使用PHP保持图像内联的修复程序。在

//Handling images
if(!empty($_FILES)){

   //Remove <> from string to set proper array key
   $inline_images=str_replace(array('<', '>'), '', $_POST['content-id-map']);

   //Get inline images
   $inline_images=json_decode($inline_images, true);

   if(!empty($inline_images)){

       foreach($inline_images as $key=>$i){
          if(isset($_FILES[$i])){

             //Now we have the inline images. You upload it to a folder or encode it base64.

            //Here is an example using base64
            $image=file_get_contents(base64_encode($_FILES[$i]['tmp_name']));

            //Now, we will str_replace the image from the email body with the encoded 6ase64 image. 

           $_POST['body-html']=str_replace('cid:'.$key, 'data:image/png;base64,'.$image, $_POST['body-html']);
        }
  }


   //Parsing actual attachments

      //Unset all inline images from attachments array
      foreach($inline_images as $i){
         unset($_FILES[$i]);
      }

       //Now, since we have removed all inline images from $_FILES. You can add your code to parse actual attachments here. 
   }
} 

好了,这是一种使用mailgun解析内联附件的简单方法。在

相关问题 更多 >