如何将matplotlib条形图作为电子邮件附件发送?

2024-04-26 22:31:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图发送一个matplotlib条形图作为电子邮件附件使用mailgun。你知道吗

条形图创建得很好,但当我试图将其保存到并作为BytesIO对象发送电子邮件时,我发现它不够。你知道吗

我尝试了以下代码:

def send_simple_message(buf):
    mgurl = 'https://api.mailgun.net/v3/{}/messages'.format('sandboxf04fcce3c4dc46c987c92f3a967e7f9c.mailgun.org')
    auth = ('api', '3701ba6d2b1ad202e76a4322a80c7600-87cdd773-683e02b1')
    files=[("attachment", ("test.jpg", buf))]
    data = {
        'from': 'Mailgun User <mailgun@{}>'.format('sandboxf04fcce3c4dc46c345c92f3a123e7f7c.mailgun.org'),
        'to': 'user@gmail.com',
        'subject': 'Simple Mailgun Example',
        'text': 'hello'
    }

    response = requests.post(mgurl, auth=auth, data=data, files=files)
    response.raise_for_status()

buf = BytesIO()

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.bar(x,y, width, color='lightblue', ec='grey')
fig.savefig(buf, format='png')
buf.seek(0)

send_simple_message(buf)

但是,它会导致以下错误:


AttributeError: 'NoneType' object has no attribute 'read'

非常感谢


Tags: orgauthsendapiformatmessagedatafig