Php Curl将字符串文件添加为帖子字段

时间:2013-04-26 19:24:11

标签: php curl mailgun

我正在使用mailGun Web API并遇到了添加内联文件的问题。 我们的软件会创建一个图像并将其作为字符串传递。我想内联那个图像 我遇到的问题是php curl接收文件指针,而不是实际文件。我希望尽可能避免编写tmp文件,因为我们有很多可以在服务器上运行的进程并且不想发送错误的电子邮件

提前致谢

MailGun内联示例:http://documentation.mailgun.net/user_manual.html#inline-image 我正在使用的代码示例:

function send_inline_image($image) {
  $ch = curl_init();

  curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  curl_setopt($ch, CURLOPT_USERPWD, 'api:key-3ax6xnjp29jd6fds4gc373sgvjxteol0');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
  curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v2/samples.mailgun.org/messages');
  curl_setopt($ch,
              CURLOPT_POSTFIELDS,
              array('from' => 'Excited User <me@samples.mailgun.org>',
                    'to' => 'sergeyo@profista.com',
                    'subject' => 'Hello',
                    'text' => 'Testing some Mailgun awesomness!',
                    'html' => '<html>Inline image: <img src="cid:test.jpg"></html>',
                    'inline' => $image))

  $result = curl_exec($ch);
  curl_close($ch);

  return $result;
 }
$image = 'Some image string that we have generated'
send_inline_image($image)

1 个答案:

答案 0 :(得分:4)

您只需要更改数组的内联参数。我已经完成了它的工作。内联参数应该是数组而不是字符串图像路径。你可以这样做:

function send_inline_image($image) {
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  curl_setopt($ch, CURLOPT_USERPWD, 'api:key-3ax6xnjp29jd6fds4gc373sgvjxteol0');
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
 curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v2/samples.mailgun.org/messages');
curl_setopt($ch,
          CURLOPT_POSTFIELDS,
          array('from' => 'Excited User <me@samples.mailgun.org>',
                'to' => 'sergeyo@profista.com',
                'subject' => 'Hello',
                'text' => 'Testing some Mailgun awesomness!',
                'html' => '<html>Inline image: <img src="cid:test.jpg"></html>',
                'inline' => array($image)//Use array instead of $image
))

   $result = curl_exec($ch);
  curl_close($ch);
  return $result;
}
$image = 'Some image string that we have generated'
send_inline_image($image)

查看评论&#34;使用数组代替$ image&#34;