python - 我需要帮助从内存中发送 Excel 附件 Mailgun

标签 python openpyxl mailgun

我正在尝试使用 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'

我应该如何更改代码?

最佳答案

工作簿不是类似文件的对象。 requests 的文件需要一个类文件对象,因此您需要首先将工作簿转换为类文件对象。您可以使用 io.BytesIO 创建内存中的类似文件的对象:

from io import BytesIO

...

bio = BytesIO()
wb.save(bio)
bio.seek(0)
send_simple_message(bio)

关于python - 我需要帮助从内存中发送 Excel 附件 Mailgun,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56501364/

相关文章:

android - 在 Heroku 上为 Parse-server-example 设置 Mailgun

Python string.join(list) 对象数组而不是字符串数组

python - 大型 jwt token 有效负载 python

python - 将混合字符串(ASCII、Unicode)输出到文件

python - 从关闭的文件中返回生成器 | csv 阅读器不返回生成器作为 openpyxl?

javascript - 尝试使用 mailgun 发送电子邮件时收到 "TypeError: undefined is not a function"

MeteorJS Mailgun Webhook 退回事件

python - 什么是 julia 中的 ".=="以及它在 python 中的等价物?

python - openpyxl : data-validation read/write without treatment

python - 如何更改日期列表中的日期格式(并在通过 openpyxl 保存到 excel 时保留该日期格式)?