Python requests: 尝试使Mailgun“发送内嵌图片”示例正常工作

2 投票
1 回答
977 浏览
提问于 2025-04-18 08:45

我在这个例子上卡住了,链接是http://documentation.mailgun.com/user_manual.html?highlight=inline%20image#sending-via-api

更新:下面的问题发生在虚拟机上,而在另一台机器上却能正常工作。

import requests
requests.post(
    "https://api.mailgun.net/v2/samples.mailgun.org/messages",
    auth=("api", "key-3ax6xnjp29jd6fds4gc373sgvjxteol0"),
    files=[("inline", open("files/test.jpg"))],
    data={"from": "Excited User <me@samples.mailgun.org>",
          "to": "bar@example.com",
          "subject": "Hello",
          "text": "Testing some Mailgun awesomness!",
          "html": '<html>Inline image here: <img src="cid:test.jpg"></html>'})

我没有改动任何代码,但它就是不工作,报错信息一堆。

注意:不要指望邮件能发送出去,但请求本身是必须要发生的!

Traceback (most recent call last):
  File "test.py", line 34, in <module>
    "html": '<html>Inline image here: <img src="cid:test.jpg"></html>'})
  File "<projectpath>/lib/python2.7/site-packages/requests/api.py", line 88, in post
    return request('post', url, data=data, **kwargs)
  File "<projectpath>/lib/python2.7/site-packages/requests/api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "<projectpath>/lib/python2.7/site-packages/requests/sessions.py", line 456, in request
    resp = self.send(prep, **send_kwargs)
  File "<projectpath>/lib/python2.7/site-packages/requests/sessions.py", line 559, in send
    r = adapter.send(request, **kwargs)
  File "<projectpath>/lib/python2.7/site-packages/requests/adapters.py", line 327, in send
    timeout=timeout
  File "<projectpath>/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 498, in urlopen
    body=body, headers=headers)
  File "<projectpath>/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 296, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "/usr/lib64/python2.7/httplib.py", line 946, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib64/python2.7/httplib.py", line 987, in _send_request
    self.endheaders(body)
  File "/usr/lib64/python2.7/httplib.py", line 940, in endheaders
    self._send_output(message_body)
  File "/usr/lib64/python2.7/httplib.py", line 801, in _send_output
    msg += message_body
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 677: ordinal not in range(128)

通过使用pdb调试工具,我发现当执行conn.request(method, url, **httplib_request_kw)时,httplib_request_kw['body']里面的字符串无法正确解码成unicode,所以请求的内容格式不对。

用curl的例子可以完美运行,但我还是更想用requests库。

另外,使用Python Requests库发送Mailgun内联图片的相关问题也有提到,但对我来说不管用。

1 个回答

0

问题出在过时的 httplib 上。

如果你遇到这个问题,建议更新一下 httplib。(把它复制到 lib/python2.7 目录下就可以了。)我的系统版本是 '2.7 (r27:82500, 2010年8月07日, 16:54:59) [GCC]',这个版本对于 python-requests 2.3.0 来说太旧了。

这可能解决了 使用 python-requests 上传文件时的 UnicodeDecodeError 问题

撰写回答