先去QQ邮箱,开启STMP服务,点击服务管理,获取自己的授权码,替换代码中的授权码
import random import datetime import schedule import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import requests # 发送邮件 def send_email( quote, sender_email, sender_password, recipient_email, smtp_server, smtp_port ): # 创建邮件内容 msg = MIMEMultipart() msg["From"] = sender_email msg["To"] = recipient_email msg["Subject"] = "每天一句至理名言" msg.attach(MIMEText(quote, "plain")) try: with smtplib.SMTP_SSL(smtp_server, smtp_port) as server: server.login(sender_email, sender_password) server.sendmail(sender_email, recipient_email, msg.as_string()) print("名言邮件已发送成功!") except Exception as e: print("发送邮件时出错:", str(e)) # 获取随机名言 def get_random_quote(api_url): try: response = requests.get(api_url) if response.status_code == 200: return response.text else: return "无法获取名言数据" except Exception as e: return "获取名言时出错:" + str(e) # 定义定时任务 def schedule_email( sender_email, sender_password, recipient_email, smtp_server, smtp_port, api_url ): def job(): quote = get_random_quote(api_url) # quote = "test" send_email( quote, sender_email, sender_password, recipient_email, smtp_server, smtp_port, ) schedule.every().day.at("16:47").do(job) # 设置每天08:00发送邮件 while True: try: schedule.run_pending() # 检查是否到达指定的退出时间,例如下午5点 now = datetime.datetime.now().time() if now.hour >= 17: break except KeyboardInterrupt: break if __name__ == "__main__": # 请在下面填写您的邮箱和配置信息 sender_email = "***@qq.com" # 发信邮箱账号 sender_password = "gnomwpicjzecficf" # 发信邮箱授权码或QQ密码 recipient_email = "---@qq.com" # 收信邮箱 smtp_server = "smtp.qq.com" # SMTP服务器地址,根据您的邮箱提供商进行更改 smtp_port = 465 # SMTP服务器端口号,根据您的邮箱提供商进行更改 api_url = "https://v1.hitokoto.cn/?c=f&encode=text" # 名言API接口地址 print(get_random_quote(api_url)) schedule_email( sender_email, sender_password, recipient_email, smtp_server, smtp_port, api_url )
搞定!