以下是一个示例代码,它遍历指定列,查找匹配项,并根据单元格值发送电子邮件。
import pandas as pd
import smtplib
from email.mime.text import MIMEText
def send_email(to_email, subject, body):
# 设置发件人邮箱和密码
from_email = 'your_email@example.com'
password = 'your_password'
# 构造邮件内容
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = to_email
# 连接SMTP服务器并发送邮件
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login(from_email, password)
server.sendmail(from_email, to_email, msg.as_string())
server.quit()
# 读取Excel文件
df = pd.read_excel('data.xlsx')
# 遍历指定列,查找匹配项并发送邮件
for index, row in df.iterrows():
if row['Column'] == '匹配项':
email = row['Email']
subject = '邮件主题'
body = '邮件内容'
send_email(email, subject, body)
上述代码首先导入所需的库,包括pandas
用于读取Excel文件,smtplib
用于发送电子邮件,email.mime.text
用于构造邮件内容。
然后定义了一个send_email
函数,该函数接收收件人邮箱、主题和正文作为参数,使用SMTP服务器发送电子邮件。
接下来,通过pd.read_excel
方法读取Excel文件。请确保已将文件名更改为实际的文件名。
在遍历指定列的循环中,使用iterrows
方法遍历数据框的每一行。如果指定列的值与"匹配项"相等,则获取该行的电子邮件地址,并调用send_email
函数发送电子邮件。
请根据实际情况修改代码中的SMTP服务器和发件人邮箱信息,并根据需要自定义邮件主题和内容。
上一篇:遍历列,并且只取一次的项目。
下一篇:遍历列,每列复制六次。