pythonemailsmtplib

How can I make the code pause 5 seconds after every email sent


I need the code to sleep every time it sends an email by 5 seconds, when I use sleep(5) it just sends all the emails and then pauses.

The code:

import pandas as pd
import smtplib
from time import sleep

SenderAddress='<xxxx@gmail.com>'

e = pd.read_excel("C:xxx/Email.xlsx")
sleep(5)
emails = e['Emails'].values
server = smtplib.SMTP("smtp.gmail.com:587")
server.starttls()
server.login('xxx@gmail.com', 'xxxxx')

msg = 'Testing the code'

subject = "Congratulations"
body = "Subject: {}\n\n{}".format(subject,msg)
for email in emails:
  server.sendmail(SenderAddress, email, body)
server.quit()

Solution

  • Try transferring the sleep method to the body of the loop. Like this

    import pandas as pd
    import smtplib
    from time import sleep
    
    SenderAddress='<xxxx@gmail.com>'
    
    e = pd.read_excel("C:xxx/Email.xlsx")
    emails = e['Emails'].values
    server = smtplib.SMTP("smtp.gmail.com:587")
    server.starttls()
    server.login('xxx@gmail.com', 'xxxxx')
    
    msg = 'Testing the code'
    
    subject = "Congratulations"
    body = "Subject: {}\n\n{}".format(subject,msg)
    for email in emails:
      server.sendmail(SenderAddress, email, body)
      sleep(5)
    server.quit()