用Python写定时发送邮件代码
时间: 2023-05-26 20:02:29 浏览: 174
以下是Python代码,可以用于定时发送邮件:
``` python
import smtplib
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 发送邮件函数
def send_email(subject, body, to_email, attachments=None):
# 邮件发送者
from_email = '发件人邮箱地址'
# 邮件对象
msg = MIMEMultipart()
# 邮件正文
body = MIMEText(body, _subtype='html', _charset='utf-8')
msg.attach(body)
# 邮件附件
if attachments:
for file in attachments:
attachment = MIMEApplication(open(file, 'rb').read())
attachment.add_header('Content-Disposition', 'attachment', filename=file)
msg.attach(attachment)
# 邮件主题、发件人、收件人
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = to_email
# SMTP服务器设置
smtp_server = 'smtp服务器地址'
smtp_port = 25
smtp_username = 'smtp服务器用户名'
smtp_password = 'smtp服务器密码'
# 发送邮件
try:
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.login(smtp_username, smtp_password)
server.sendmail(from_email, to_email, msg.as_string())
print(f'{time.strftime("%Y-%m-%d %H:%M:%S")} 邮件发送成功')
except Exception as e:
print(f'{time.strftime("%Y-%m-%d %H:%M:%S")} 邮件发送失败:{e}')
# 设置邮件主题、收件人、邮件内容和附件
subject = '邮件主题'
to_email = '收件人邮箱地址'
body = '邮件内容'
attachments = ['附件1路径', '附件2路径']
# 设置发送时间
send_time = '2022-01-01 00:00:00'
# 定时发送邮件
while True:
now_time = time.strftime('%Y-%m-%d %H:%M:%S')
if now_time == send_time:
send_email(subject, body, to_email, attachments)
break
else:
print(f'{now_time} 邮件未发送!')
time.sleep(1)
```
首先,我们定义了一个`send_email`函数,用于发送邮件。该函数需要传入邮件主题、邮件内容、收件人邮箱以及可选的附件。邮件发送使用的是SMTP协议,需要设置SMTP服务器地址、SMTP端口、SMTP用户名和SMTP密码。
接着,我们设置了邮件主题、收件人邮箱、邮件内容和附件信息。注意,如果没有附件,需要将`attachments`参数设置为`None`。
然后,我们设置了定时发送的时间。在`while`循环中,每秒钟检查当前时间是否等于要发送的时间,如果相等,则调用`send_email`函数发送邮件,并退出循环。如果不相等,则打印当前时间,并等待1秒钟后再次检查。
阅读全文