我怎样才能使这个 smtplib 代码在无限循环中发送电子邮件?

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

我如何调整下面的代码以在无限循环中向给定的收件人发送电子邮件?。我在下面尝试过,但出现错误:

# 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'] = "example1@hotmail.com"
msg['To'] = "example2@hotmail.com"

# Login
s =server = smtplib.SMTP('smtp.office365.com', 587)
s.starttls()
s.login('example1@hotmail.com',"password")

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

i = i + 1

这里有几个问题:

  1. While 循环未正确缩进(但也许这是 StackOveflow 中的 copy/paste 格式错误?)
  2. SMTP 连接在循环之前启动一次,但在循环中的每次迭代时退出。 (要么在整个循环中保持打开状态,要么在每次迭代中连接并退出)。

这是包含上述修复的更新代码(未经测试):

# 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'] = "example1@hotmail.com"
msg['To'] = "example2@hotmail.com"
    
i = 0
while True:
    # Login
    s =server = smtplib.SMTP('smtp.office365.com', 587)
    s.starttls()
    s.login('example1@hotmail.com',"password")

    # Sending the message
    s.send_message(msg)

    s.quit()  
    i = i + 1