Python请求:尝试制作Mailgun"发送内嵌图像"样本工作

时间:2014-06-05 16:49:15

标签: python python-requests mailgun

我坚持使用http://documentation.mailgun.com/user_manual.html?highlight=inline%20image#sending-via-api

中的示例

UPD:下面的问题发生在虚拟机上,而它在另一个上运行。

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,因此正文格式不正确。

卷曲示例效果很好,但我确实更喜欢使用请求。

PS:Sending Mailgun Inline Images in HTML using Python Requests library涉及,但不适合我。

1 个答案:

答案 0 :(得分:0)

问题已经过时了httplib。

如果你遇到这个问题 - 请记住获取新的httplib。 (复制到lib / python2.7似乎就足够了。)我的sys.version是&#39; 2.7(r27:82500,2010年8月7日,16:54:59)[GCC]&#39;它对于python-requests 2.3.0而言太旧了。

可能解决Uploading file with python-requests - UnicodeDecodeError