首页 > 解决方案 > 如何使用for循环win32 python在邮件正文中附加多个嵌入图像

问题描述

我正在从 excel 中导出图像,并且我想将 Outlook 电子邮件中的所有图像作为嵌入图像附加。我的代码在导出图像的下方,但是在添加到邮件正文时,仅附加了最后一张图像。作为附件发送时,所有图像都被选中。

from PIL import ImageGrab
import win32com.client as win32
import xlrd
from win32com import client
import base64

path=
excel =win32.DispatchEx('Excel.Application')
workbook = excel.Workbooks.Open("path to file")
RNC = xlrd.open_workbook("path to file")
outlook = client.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail = outlook.CreateItem(0)
mail.Display() # required to paste chart
mail.To = 'xyz'
mail.Subject = 'Daily Report'
#exporting images from excel
l=[]
RNC_list = RNC.sheet_by_name('Sheet1')
for x in range(1,RNC_list.nrows):
    for cell in RNC_list.row(x):
        l.append(cell.value)
for sheet in workbook.Worksheets:
    if sheet.name in l:
        for i, shape in enumerate(sheet.Shapes):
            if shape.Name.startswith('Picture'):
                shape.Copy()
                image = ImageGrab.grabclipboard()
                image.save(path + r"\Pic" + sheet.name+str(i) + ".png")
                filename = path + r"\Pic" + sheet.name+str(i) + ".png"
                attachment= mail.Attachments.Add(filename)
                attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "{}".format(r"\Pic" + sheet.name+str(i)))
                mail.HTMLBody = "<br><br><h4> <img src=""cid:{}"" height=""300"" width=""870""><br>".format(r"\Pic" + sheet.name+str(i))
workbook.Close()                
del workbook
del excel
print("Done")

目前,仅嵌入最后一张图像。我需要将所有导出的图像嵌入邮件正文中。

标签: pythonemailwin32com

解决方案


推荐阅读