在 Python 中发送带有嵌入式图像的邮件

sending mail with embedded images in python

提问人:Chance8 提问时间:10/22/2023 最后编辑:marc_sChance8 更新时间:10/22/2023 访问量:53

问:

编辑:我发现了异常错误。只有一个问题,所以我编辑了这个问题

我是个蟒蛇白痴。需要遍历我的 Excel 文件以从每行中读取不确定数量的列。

对于问题 2:在 excel 文件上循环访问列数 3 到 7。文件1、文件2、文件3、文件4。(这些表示图像文件的(字符串)文件名。File2 到 File4 可能是 nan。所以不确定 excel 中每行有多少张图像)

from email.message import EmailMessage
from email.utils import make_msgid
import smtplib
import ssl
import pandas as pd

# change these as per
your_email = "[email protected]"
your_password = "***"

# reading the spreadsheet
email_list = pd.read_excel('C:/path/to/file/student_list1.xlsx')
img_path = r'C:/path/to/image/'

# getting the names and the emails
names = email_list['Student Name']
parentgs = email_list['Parent']
emails = email_list['E-mail']

# iterate through the records
for i in range(len(names)):
    name = names[i]
    email = emails[i]

    image1 = email_list['File1']  # there may be up to 3 more images

    img1 = image1[i]
    imgwpath = os.path.join(img_path, img1) # again, might be up to 3 more

    parentgs.fillna(" ")
    parentorguard = parentgs[i]

    email_message = EmailMessage()
    email_message['From'] = your_email
    email_message['To'] = email
    email_message['Bcc'] = '[email protected]'
    email_message['Subject'] = 'Test. sent from Python'

    img_cid = make_msgid()
    email_message.set_content("""\
        <html>
            <p>Dear """ + parentorguard + """
            <p>We have some additional html here</p>
            <img src="cid:img_cid", width="10%" height="7%" float: left>
        </html>
    """.format(email=email, image_cid=img_cid), subtype='html')

    #NEED LOOP TO READ THROUGH COLUMN 4 TO COLUMN 7 OF THE EXCEL FILE.  (COLS 6 AND 7 MIGHT BE nan
    #I am not sure how to loop through undetermined number of rows.  So possibly 3 more images to a
    #add to <html> section above :o

    with open(imgwpath, 'rb') as fp:
        email_message.add_related(fp.read(), maintype="image",
            subtype="jpeg",
            cid = f"<img_cid>")

    email_string = email_message.as_string()

    # Connect to the Gmail SMTP server and Send Email
    context = ssl.create_default_context()
    with smtplib.SMTP_SSL("smtp.ionos.com", 465, context=context) as server:
        server.login(your_email, your_password)
        server.sendmail(your_email, email, email_string)
python smtplib 发送消息

评论

0赞 jlandercy 10/22/2023
问题是什么?问题是什么?
0赞 Chance8 10/23/2023
此代码仅包含一个图像。excel 文件的每一行中最多可以引用 4 个图像。因此,我需要以某种方式遍历每行不确定的列数,以获取要包含在电子邮件中的其余图像。

答: 暂无答案