'How can I make this smtplib code send emails in an infinite loop?

How can I adjust the code below to send emails to the given recipient in an infinite loop?. I have tried below but I am getting an error:

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.message import EmailMessage

# Open the plain text file whose name is in textfile for reading.
with open(r'C:\Users\David\Documents\Hello.txt') as fp:
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(fp.read())

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'yes'
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"

# Login
s =server = smtplib.SMTP('smtp.office365.com', 587)
s.starttls()
s.login('[email protected]',"password")

i = 0
while True:
# Sending the message
s.send_message(msg)
s.quit()

i = i + 1


Solution 1:[1]

There are a couple of problems here:

  1. While loop not properly indented (but maybe that was a copy/paste formatting error into StackOveflow?)
  2. SMTP connection is started once, before the loop but quit on every iteration within the loop. (Either keep it open for the whole loop or connnect and quit within each iteration).

Here's updated code (untested) with the above fixes:

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.message import EmailMessage

# Open the plain text file whose name is in textfile for reading.
with open(r'C:\Users\David\Documents\Hello.txt') as fp:
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(fp.read())

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'yes'
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"
    
i = 0
while True:
    # Login
    s =server = smtplib.SMTP('smtp.office365.com', 587)
    s.starttls()
    s.login('[email protected]',"password")

    # Sending the message
    s.send_message(msg)

    s.quit()  
    i = i + 1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ma499