我正在尝试使用Python和Mailgun Rest API发送带有Excel附件的电子邮件。
想法是使用openpyxl创建excel文件,然后将存储在python内存中的excel工作簿作为附件发送。
非常感谢
import workbook from openpyxl
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws['A1'] = 42
def send_simple_message(wb):
return requests.post(
"https://api.mailgun.net/v3/sandboxf04fcce3c4dc46c987c92f3a967e7f9c.mailgun.org/messages",
files = [("attachment", ("test.xlsx", wb))],
auth = ("api", "3701ba6d2b1ad202e76a4322a80c7600-87cdd4445-897e02b1"),
data = {
"from": "Excited User <mailgun@sandboxf04brede3c4dc46c987c92f3a967e7f9c.mailgun.org>",
"to": "exampleemail@gmail.com",
"subject": "Hello",
"text": 'hello'
})
send_simple_message(wb)
它导致了以下回溯错误:
File "<ipython-input-39-5dc97cf501dc>", line 1, in <module>
send_simple_message(wb)
File "<ipython-input-37-fc3ec9cbb304>", line 9, in send_simple_message
"text": 'hello'})
File "/Users/willpeebles/anaconda/lib/python3.5/site-packages/requests/api.py", line 112, in post
return request('post', url, data=data, json=json, **kwargs)
File "/Users/willpeebles/anaconda/lib/python3.5/site-packages/requests/api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "/Users/willpeebles/anaconda/lib/python3.5/site-packages/requests/sessions.py", line 504, in request
prep = self.prepare_request(req)
File "/Users/willpeebles/anaconda/lib/python3.5/site-packages/requests/sessions.py", line 436, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "/Users/willpeebles/anaconda/lib/python3.5/site-packages/requests/models.py", line 305, in prepare
self.prepare_body(data, files, json)
File "/Users/willpeebles/anaconda/lib/python3.5/site-packages/requests/models.py", line 499, in prepare_body
(body, content_type) = self._encode_files(files, data)
File "/Users/willpeebles/anaconda/lib/python3.5/site-packages/requests/models.py", line 158, in _encode_files
fdata = fp.read()
AttributeError: 'Workbook' object has no attribute 'read'
我应该如何更改代码?
答案 0 :(得分:0)
工作簿不是类似文件的对象。请求的文件需要一个类似文件的对象,因此您需要先将工作簿转换为类似文件的对象。您可以使用io.BytesIO创建内存中类似文件的对象:
from io import BytesIO
...
bio = BytesIO()
wb.save(bio)
bio.seek(0)
send_simple_message(bio)