3

我使用mailgun发送邮件。我尝试使用 python api

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})

但它无法发送图像。

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

 �PNG


 none

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

all content of a.text
none

为什么png文件不被读取?

4

3 回答 3

3

打开图片必须是:

open(pwd,"rb")

以二进制模式读取它。

于 2014-08-08T21:06:06.653 回答
1
open(pwd,"rb")

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

于 2014-08-09T06:35:31.393 回答
1

回答这个问题有点晚了,但我也在寻找解决方案,但在网上找不到任何解决方案。我已经编写了自己的代码,并教我在这里分享。

当 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 解析内联附件的简单方法。

于 2016-06-10T22:33:51.120 回答