我已经汇总了一个代码,可以向多个收件人发送电子邮件。但是,每个收件人都会收到所有邮件,而不是他自己的邮件。
数据框:
email content
mark@gmail.com Hi Mark, bla bla
eve@gmail.com Hi Eve, bla bla
john@gmail.com Hi, John bla bla
for content in df['content']:
for email in df['email']:
message = MIMEMultipart()
message['Subject'] = "Subject"
message['From'] = 'my email'
message['Reply-to'] = 'my email'
message['To'] = '{}'.format(email)
text = MIMEText(mail)
message.attach(text)
server = smtplib.SMTP ('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.login(login, password)
server.sendmail(message['From'], message['To'], message.as_string())
server.quit()
答案 0 :(得分:0)
试试这个:
df = {
'content': ['test1', 'test2', 'test3'],
'email': ['mail1@mail.com', 'mail2@mail.com', 'mail3@mail.com']
}
x = 0
for email in df['email']:
print(email)
print(df["content"][x]+"\n")
x+=1
答案 1 :(得分:0)
只需zip
个列并省略一个循环:
for email, content in zip(df['email'], df['content']):
message = MIMEMultipart()
message['Subject'] = "Subject"
message['From'] = 'my email'
message['Reply-to'] = 'my email'
message['To'] = '{}'.format(email)
text = MIMEText(mail)
message.attach(text)
server = smtplib.SMTP ('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.login(login, password)
server.sendmail(message['From'], message['To'], message.as_string())
server.quit()
答案 2 :(得分:0)
我正在迭代它两次。而不是使用2 for循环,迭代DataFrame的正确方法是使用
而不是:
for content in df['content']:
for email in df['email']:
使用此:
for c in df.itertuples():
message = MIMEMultipart()
message['To'] = '{}'.format(c[0])
text = MIMEText(c[1])
message.attach(text)