0

I have put together a code to send emails to multiple recipients. However each recipient receives all mails instead of his own.

Dataframe:

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()
Lucia Commerz
  • 73
  • 1
  • 2
  • 7
  • 1
    You are iterating twice. Once over content and once over e-mail. Basically you are sending all possible combinations of content vs email. To do this with a for loop, iterate only once over all rows. Take a look at this answer: https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas – rafaelc Jun 09 '18 at 13:22
  • Thanks @RafaelC! – Lucia Commerz Jun 09 '18 at 13:58

3 Answers3

0

Try this:

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
paradox
  • 634
  • 5
  • 13
0

Just zip columns together and omit one loop:

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()
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

I was iterating it twice. Instead of using 2 for loops, the correct way to iterate through out DataFrame is using

Instead of this:

for content in df['content']:
    for email in df['email']:

Use this:

for c in df.itertuples():
   message = MIMEMultipart()
   message['To'] = '{}'.format(c[0])

   text = MIMEText(c[1])
   message.attach(text)
Lucia Commerz
  • 73
  • 1
  • 2
  • 7