在电子邮件正文中附加图像和数据框

时间:2018-05-21 13:17:31

标签: python

我正在尝试将图像和数据框附加到电子邮件正文中。我可以参考Sending Multipart html emails which contain embedded imagesSend table as an email body (not attachment ) in Python单独发送它们。尝试了不同的事情,但没有一点起作用。

from email.message import EmailMessage
from email.utils import make_msgid
import mimetypes

msg = EmailMessage()

# generic email headers
msg['Subject'] = 'Hello there'
msg['From'] = 'abhishek.gupta1608@gmail.com'
msg['To'] = 'abhishek.gupta@pharmeasy.in'

# set the plain text body
msg.set_content('This is a plain text body.')

# now create a Content-ID for the image
image_cid = make_msgid(domain='xyz.com')
# if `domain` argument isn't provided, it will 
# use your computer's name

# set an alternative html body
msg.add_alternative("""\
<html>
<head>
<style> 
 table, th, td {{ border: 1px solid black; border-collapse: collapse; }}
  th, td {{ padding: 5px; }}
</style>
</head>
    <body>
        <p>This is an HTML body.<br>
        {table}
        </p>
        <img src="cid:{image_cid}">
    </body>
</html>
""".format(image_cid=image_cid[1:-1]), subtype='html')
# image_cid looks like <long.random.number@xyz.com>
# to use it as the img src, we don't need `<` or `>`
# so we use [1:-1] to strip them off


# now open the image and attach it to the email
with open('/Users/abhishekgupta/mybarchart.png', 'rb') as img:

    # know the Content-Type of the image
    maintype, subtype = mimetypes.guess_type(img.name)[0].split('/')

    # attach it
    msg.get_payload()[1].add_related(img.read(), 
                                         maintype=maintype, 
                                         subtype=subtype, 
                                         cid=image_cid)


# the message is ready now
# you can write it to a file
# or send it using smtplib

col_list = list(df_2.columns.values)
data = df_2
# above line took every col inside csv as list
html = html.format(table=tabulate(data, headers=col_list, tablefmt="html"))

KeyError                                  Traceback (most recent call last)
<ipython-input-50-151b9f8e84e8> in <module>()
     33     </body>
     34 </html>
---> 35 """.format(image_cid=image_cid[1:-1]), subtype='html')
     36 # image_cid looks like <long.random.number@xyz.com>
     37 # to use it as the img src, we don't need `<` or `>`

KeyError: 'table'

0 个答案:

没有答案
相关问题