mailgun 发送内嵌图片无法正常工作?

3 投票
3 回答
2161 浏览
提问于 2025-04-18 16:36

我用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文件不能被读取呢?

3 个回答

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

1
open(pwd,"rb")

你可以使用这个链接:https://stackoverflow.com/a/23566951/3726821

3

打开图片时,必须使用:

open(pwd,"rb")

以二进制模式读取它。

撰写回答