python定时发送邮件
时间: 2023-08-28 07:04:38 浏览: 45
可以使用Python的smtplib和datetime模块来实现定时发送邮件。
首先,需要导入相应的模块:
```python
import smtplib
import datetime
```
接下来,需要设置发送邮件的基本信息,包括发件人、收件人、邮箱服务器地址以及登录邮箱的账号和密码。
```python
# 发件人邮箱地址
sender = 'your_email_address'
# 收件人邮箱地址
receivers = ['recipient1@example.com', 'recipient2@example.com']
# 邮箱服务器地址
smtp_server = 'smtp.example.com'
# 登录邮箱的账号和密码
username = 'your_username'
password = 'your_password'
```
然后,可以设置定时发送邮件的时间,这里以每天的早上9点为例。
```python
# 设置每天的定时发送时间(这里设置为早上9点)
send_time = datetime.datetime.now().replace(hour=9, minute=0, second=0, microsecond=0)
# 如果当前时间已经过了定时发送时间,则将定时发送时间改为明天的早上9点
if send_time < datetime.datetime.now():
send_time += datetime.timedelta(days=1)
```
最后,可以编写发送邮件的函数,并在定时发送时间到达时调用该函数发送邮件。
```python
# 发送邮件的函数
def send_email():
# 创建SMTP连接对象
smtp_obj = smtplib.SMTP(smtp_server, 587)
# 打印与邮箱服务器的交互信息
smtp_obj.set_debuglevel(True)
# 进行SMTP连接
smtp_obj.starttls()
smtp_obj.login(username, password)
# 编写邮件内容
subject = 'Python定时发送邮件测试'
content = '这是一封定时发送的测试邮件。'
message = 'Subject: {}\n\n{}'.format(subject, content)
# 发送邮件
smtp_obj.sendmail(sender, receivers, message)
# 关闭SMTP连接
smtp_obj.quit()
# 等待定时发送时间到达,然后发送邮件
while True:
if datetime.datetime.now() >= send_time:
send_email()
break
```
完整的代码如下:
```python
import smtplib
import datetime
# 发件人邮箱地址
sender = 'your_email_address'
# 收件人邮箱地址
receivers = ['recipient1@example.com', 'recipient2@example.com']
# 邮箱服务器地址
smtp_server = 'smtp.example.com'
# 登录邮箱的账号和密码
username = 'your_username'
password = 'your_password'
# 设置每天的定时发送时间(这里设置为早上9点)
send_time = datetime.datetime.now().replace(hour=9, minute=0, second=0, microsecond=0)
# 如果当前时间已经过了定时发送时间,则将定时发送时间改为明天的早上9点
if send_time < datetime.datetime.now():
send_time += datetime.timedelta(days=1)
# 发送邮件的函数
def send_email():
# 创建SMTP连接对象
smtp_obj = smtplib.SMTP(smtp_server, 587)
# 打印与邮箱服务器的交互信息
smtp_obj.set_debuglevel(True)
# 进行SMTP连接
smtp_obj.starttls()
smtp_obj.login(username, password)
# 编写邮件内容
subject = 'Python定时发送邮件测试'
content = '这是一封定时发送的测试邮件。'
message = 'Subject: {}\n\n{}'.format(subject, content)
# 发送邮件
smtp_obj.sendmail(sender, receivers, message)
# 关闭SMTP连接
smtp_obj.quit()
# 等待定时发送时间到达,然后发送邮件
while True:
if datetime.datetime.now() >= send_time:
send_email()
break
```
注意,这种定时发送邮件的方式需要保持程序一直运行,可以在服务器上部署该程序来实现每天定时发送邮件的功能。