我想制作一个Python脚本,每30分钟发送一封带有附件(txt)的电子邮件。这是我的代码,用于发送带有附件的电子邮件。它的工作没有任何问题。但是,我需要帮助弄清楚如何按时发送此邮件。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os.path
email = 'myaddress@gmail.com'
password = 'password'
send_to_email = 'sentoaddreess@gmail.com'
subject = 'This is the subject'
message = 'This is my message'
file_location = 'C:\\Users\\You\\Desktop\\attach.txt'
msg = MIMEMultipart()
msg['From'] = email
msg['To'] = send_to_email
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
filename = os.path.basename(file_location)
attachment = open(file_location, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, send_to_email, text)
server.quit()
答案 0 :(得分:1)
为您提供两个选择
选项二是使用time.sleep()函数。这种方法意味着脚本将继续运行,每30分钟发送一封电子邮件。当您想停止电子邮件时,必须停止脚本。
import time
while True:
{insert your email send code here}
time.sleep(60*30) # this is in seconds, so 60 seconds x 30 mins