Python Matplotlib to smtplib

前端 未结 2 1261
你的背包
你的背包 2020-12-16 00:13

I\'m wondering if I can send out a matplotlib pyplot through smtplib. What I mean is, after I plot this dataframe:

In [3]: dfa
Out[3]:
           day      i         


        
相关标签:
2条回答
  • 2020-12-16 00:48

    You can use figure.savefig() to save your plot to a file. An example where I output a plot to a file:

    fig = plt.figure()    
    ax = fig.add_subplot(111)
    
    # Need to do this so we don't have to worry about how many lines we have - 
    # matplotlib doesn't like one x and multiple ys, so just repeat the x
    lines = []
    for y in ys:
        lines.append(x)
        lines.append(y)
    
    ax.plot(*lines)
    
    fig.savefig("filename.png")
    

    Then just attach the image to your email (like the recipe in this answer).

    0 讨论(0)
  • 2020-12-16 00:57

    It is also possible to do everything in memory saving to a BytesIO buffer and then feeding the payload with it:

    import io
    from email.encoders import encode_base64
    from email.mime.base import MIMEBase
    from email.mime.multipart import MIMEMultipart
    
    buf = io.BytesIO()
    plt.savefig(buf, format = 'png')
    buf.seek(0)
    
    mail = MIMEMultipart()
    ...
    part = MIMEBase('application', "octet-stream")
    part.set_payload( buf.read() )
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % 'anything.png')
    mail.attach(part)
    
    0 讨论(0)
提交回复
热议问题