用python写一个自动定时发送邮件代码
时间: 2023-05-23 21:03:48 浏览: 135
好的,以下是用 Python 实现的自动定时发送邮件的代码:
```python
import smtplib
import datetime
import time
# 发送方的邮箱信息
sender_email = "your_email@example.com"
sender_password = "your_email_password"
# 接收方的邮箱信息
receiver_email = "recipient_email@example.com"
# 邮件主题和内容
subject = "Test Email"
body = "This is a test email sent by Python."
# 发送邮件的函数
def send_email():
# 连接 SMTP 服务器
server = smtplib.SMTP("smtp.gmail.com", 587) # 以 Gmail 为例
server.ehlo()
server.starttls()
server.login(sender_email, sender_password)
# 构造邮件内容
message = f"Subject: {subject}\n\n{body}"
# 发送邮件
server.sendmail(sender_email, receiver_email, message)
print("Email sent successfully!")
# 断开连接
server.quit()
# 设置定时发送邮件的时间
scheduled_time = datetime.datetime(2022, 8, 1, 9, 0, 0) # 发送时间为 2022 年 8 月 1 日早上 9 点
# 等待到达发送时间
while datetime.datetime.now() < scheduled_time:
time.sleep(1)
# 发送邮件
send_email()
```
以上代码会在设定的时间自动发送一封邮件,你可以根据需要修改邮件内容、收发邮箱等参数。