定时运行python脚本并发送邮件_python实现定时发送邮件到指定邮箱
时间: 2023-07-30 18:12:47 浏览: 174
可以使用Python中的smtplib和schedule模块实现定时发送邮件到指定邮箱。
首先,需要安装smtplib和schedule模块,可以使用以下命令进行安装:
```
pip install smtplib
pip install schedule
```
接下来,可以使用以下代码实现定时发送邮件功能:
```python
import smtplib
import schedule
import time
def send_email():
# 设置邮箱地址和密码
from_email = 'your_email@example.com'
password = 'your_email_password'
# 设置收件人地址
to_email = 'recipient_email@example.com'
# 设置邮件内容
subject = 'Test Email'
body = 'This is a test email sent by Python.'
# 登录邮箱服务器
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login(from_email, password)
# 发送邮件
message = 'Subject: {}\n\n{}'.format(subject, body)
server.sendmail(from_email, to_email, message)
# 关闭连接
server.quit()
# 设置定时任务
schedule.every().day.at('08:00').do(send_email)
while True:
schedule.run_pending()
time.sleep(1)
```
在上面的代码中,send_email()函数用来发送邮件,其中需要设置发件人的邮箱地址和密码,以及收件人的邮箱地址。同时,还需要设置邮件的主题和内容。
使用schedule模块的every().day.at()方法可以设置定时任务的时间,这里设置为每天8点执行send_email()函数。最后,在主循环中使用schedule.run_pending()方法可以执行定时任务。
注意,在使用该代码前需要将from_email和password替换为自己的邮箱地址和密码,同时也需要设置正确的SMTP服务器地址。
希望这个代码对你有帮助!
阅读全文
相关推荐


















