python - 如何在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)
解决方案
您可以使用 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)
推荐阅读
- html - 引导设计查询
- php - 将变量从 jQuery 保存到 PHP
- airflow - 气流返回列表索引超出范围
- r - 试图找到岭回归的测试和训练误差作为样本量的函数
- sql - SQL Server - 调试 SQL WHERE 子句
- php - (PHPUnit) PHP 致命错误:未捕获的错误:调用未定义的函数 each()
- excel - 使用 VBA 对数据透视表进行多个过滤器
- ionic-framework - 关于离子使用“mousedown”,“mousemove”的问题
- python - 仅限 Python 属性设置器
- azure-cognitive-search - 索引器的 Azure 搜索硬删除策略