首页 > 解决方案 > 如何在for循环中遍历两个变量

问题描述

我的问题是,当我发送电子邮件时,它应该根据电子邮件地址和存储在 excel 电子表格中的字段给出不同的名称。假设我的电子表格中只有两个收件人。我将如何获得以下预期输出?谢谢

现在输出:
Hi, John Smith David Wilson, I hope you received this e-mail with the attachment.
Hi, John Smith David Wilson, I hope you received this e-mail with the attachment.

预期输出:
Hi, John Smith, I hope you received this e-mail with the attachment.
Hi, David Wilson, I hope you received this e-mail with the attachment.

from email.message import EmailMessage
import pandas as pd

sender_email = input("Enter your e-mail address: ")
password = input("Enter your password: ")

email_list = pd.read_excel("D:\Learning Python\Mini_Projects\emailaddresses.xlsx", engine="openpyxl")
names = email_list['Name']
emails = email_list['Email']
count = 0
for email in emails:
    msg = EmailMessage()
    msg['Subject'] = "Piano Concert Coming Soon by Jabob!"
    msg['From'] = sender_email
    msg['To'] = email
    msg.set_content(f"""\
Hi {", ".join(names)}, I hope you received this e-mail with the attachment""")


    with open('TrainingProgram.pdf', 'rb') as f:
        file_data = f.read()
        file_name = f.name

        msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(sender_email, password)
        smtp.send_message(msg)
    count += 1
    print("E-mail Sent: ", count)

标签: pythonemail

解决方案


您可以使用 zip:

names = ["John", "Mike"]
emails = ["John@work.com", "Mike@work.com"]
count = 0
for email, name in zip(emails, names):
    print(f"""Hi {name}, I hope you received this e-mail with the attachment""")

    count += 1
    print("E-mail Sent to %s: " % email, count)

推荐阅读