用Python 写一个定时发送邮件的代码
时间: 2023-05-23 12:03:07 浏览: 91
python定时利用QQ邮件发送天气预报的实例
好的,以下是用 Python 写一个定时发送邮件的代码的示例:
```python
import smtplib
import datetime
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 发件人邮箱地址
sender = 'your_email@example.com'
# 接收人邮箱地址
receiver = 'recipient_email@example.com'
# 发件人邮箱的SMTP服务器地址,根据邮件服务商不同可能会有所调整
smtp_server = 'smtp.example.com'
# 发件人邮箱的SMTP服务器端口
smtp_port = 587
# 发件人邮箱账号和密码
username = 'your_username'
password = 'your_password'
# 邮件正文
text = 'email text content'
# 创建带附件的邮件实例
msg = MIMEMultipart()
# 设置邮件标题、发件人、收件人、时间等信息
msg['Subject'] = 'email subject'
msg['From'] = sender
msg['To'] = receiver
msg['Date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 添加邮件正文
msg.attach(MIMEText(text))
# 添加附件
filename = 'attachment.txt'
with open(filename, 'rb') as f:
attachment = MIMEApplication(f.read(), Name=filename)
attachment['Content-Disposition'] = 'attachment; filename="%s"' % filename
msg.attach(attachment)
# 连接SMTP服务器,登录发件人邮箱账号
smtp = smtplib.SMTP(smtp_server, smtp_port)
smtp.starttls()
smtp.login(username, password)
# 定时发送邮件
while True:
now = datetime.datetime.now()
if now.hour == 8 and now.minute == 0:
smtp.sendmail(sender, receiver, msg.as_string())
print('Email sent at %s' % now)
break
else:
print('Current time is %s, waiting for 1 minute' % now)
time.sleep(60)
# 关闭SMTP连接
smtp.quit()
```
这段代码可以每天 8 点定时发送一封带附件的邮件。你可以根据自己的需求修改发送时间、收件人、邮件正文、附件等内容。
阅读全文