Python循环遍历html文件并为电子邮件嵌入图像

问题描述 投票:-2回答:1

因此,我的目标是能够将html文件作为内容正文而不是附件进行邮寄。我正在处理的html文件具有嵌入式图像。我采用这种方法的原因是html文件再次受到更改。以下是代码

from email.mime.text import MIMEText
from email.MIMEImage import MIMEImage
from email.mime.multipart import MIMEMultipart
import smtplib
from bs4 import BeautifulSoup
from os.path import basename, splitext


fromaddr = "[email protected]"
toaddr = "[email protected]"


html = open("Welcome_to_the_Environment.htm")
msg= MIMEMultipart('imageandtext')
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Automatic Weekly Report"
msgText = MIMEText(html.read(), 'html')
msg.attach(msgText)
my_html_string = html.read()

soup = BeautifulSoup(msg.as_string())
msgImage = [{}for img in soup.findAll('img')]
i=0
for img in soup.findAll('img'):
    imgname = str(img['src'])
    img['src'] = 'cid:' + splitext(basename(img['src']))[0]
    fp = open("Welcome_to_the_Environment_files\\" + imgname, 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()

    # Define the image's ID as referenced above
    msgImage[i].add_header('Content-ID', (splitext(basename(img['src']))[0])
    msg.attach(msgImage[i])
    i=i+1
my_html_string = str(soup)


debug = False
if debug:
    print(msg.as_string())
else:
    server = smtplib.SMTP('smtp.example.com',5)
    text = msg.as_string()
    server.sendmail(fromaddr, toaddr, text)
    server.quit()

但是我在msg.attach(msgImage [i])行遇到语法错误。是因为我将图像附加在循环内吗?还是我做错了其他事?

python html email mime mimemultipart
1个回答
0
投票

如上文@ Julien所述。错误在于括号。

© www.soinside.com 2019 - 2024. All rights reserved.