本文目录导读:

准备工作
- 安装所需库:
pip install imaplib email plyer schedule
imaplib:用于连接 IMAP 邮件服务器。email:解析邮件内容。plyer:发送桌面通知。schedule:设置定时任务。
完整脚本
import imaplib
import email
from email.header import decode_header
import schedule
import time
from plyer import notification
# 邮箱配置
EMAIL = "your_email@example.com" # 替换为你的邮箱
PASSWORD = "your_password" # 替换为你的密码(或应用专用密码)
IMAP_SERVER = "imap.example.com" # 如 outlook.office365.com / imap.gmail.com
IMAP_PORT = 993
# 已通知的邮件ID集合(避免重复提醒)
notified_ids = set()
def decode_subject(subject):
"""解码邮件主题"""
if subject is None:
return "(无主题)"
decoded_parts = decode_header(subject)
decoded_subject = ""
for part, encoding in decoded_parts:
if isinstance(part, bytes):
try:
decoded_subject += part.decode(encoding or "utf-8", errors="ignore")
except:
decoded_subject += part.decode("utf-8", errors="ignore")
else:
decoded_subject += part
return decoded_subject
def check_mail():
"""检查未读邮件并发送桌面通知"""
global notified_ids
try:
# 连接IMAP服务器
mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
mail.login(EMAIL, PASSWORD)
mail.select("INBOX")
# 搜索所有未读邮件
status, messages = mail.search(None, "UNSEEN")
if status != "OK":
print("搜索邮件失败")
return
email_ids = messages[0].split()
if not email_ids:
print("没有新邮件")
return
print(f"发现 {len(email_ids)} 封未读邮件")
for e_id in email_ids:
e_id_str = e_id.decode()
if e_id_str in notified_ids:
continue # 跳过已通知的邮件
# 获取邮件内容
status, data = mail.fetch(e_id, "(RFC822)")
if status != "OK":
continue
for response_part in data:
if isinstance(response_part, tuple):
msg = email.message_from_bytes(response_part[1])
subject = decode_subject(msg["Subject"])
from_ = msg.get("From", "未知发件人")
# 发送桌面通知
notification.notify(
title=f"新邮件:{from_}",
message=subject[:50] + ("..." if len(subject) > 50 else ""),
timeout=10
)
# 记录已通知的邮件ID
notified_ids.add(e_id_str)
# 控制台输出
print(f"新邮件:{subject} - 来自:{from_}")
mail.logout()
except Exception as e:
print(f"检查邮件时出错:{e}")
def main():
"""定时任务主程序"""
# 立即执行一次检查
check_mail()
# 每5分钟检查一次(可根据需要调整)
schedule.every(5).minutes.do(check_mail)
print("邮件监控已启动...")
while True:
schedule.run_pending()
time.sleep(1)
if __name__ == "__main__":
main()
使用说明
-
修改配置:
- 将
EMAIL和PASSWORD替换为你的邮箱账号和密码(建议使用应用专用密码,尤其是Gmail/Outlook)。 - 设置正确的
IMAP_SERVER:- Gmail:
imap.gmail.com - Outlook/Hotmail:
outlook.office365.com - QQ邮箱:
imap.qq.com - 163邮箱:
imap.163.com
- Gmail:
- 将
-
运行脚本:
python email_checker.py
-
定时检查:默认每5分钟检查一次,可通过修改
schedule.every(5).minutes.do(check_mail)中的数字调整。
自定义提醒方式
除了桌面通知,你还可以添加其他提醒方式:
发送到手机(通过Pushbullet)
import requests
def send_pushbullet(title, body):
"""通过Pushbullet发送到手机"""
api_key = "your_pushbullet_api_key"
headers = {"Access-Token": api_key, "Content-Type": "application/json"}
data = {"title": title, "body": body, "type": "note"}
requests.post("https://api.pushbullet.com/v2/pushes", json=data, headers=headers)
发送到Telegram
def send_telegram(message):
"""通过Telegram Bot发送"""
bot_token = "your_bot_token"
chat_id = "your_chat_id"
url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
data = {"chat_id": chat_id, "text": message}
requests.post(url, json=data)
播放声音提醒(Windows)
import winsound
def play_alert():
"""播放系统警告音"""
winsound.MessageBeep(winsound.MB_ICONEXCLAMATION)
安全注意事项
- 密码安全:不要将密码硬编码在脚本中,建议使用环境变量或配置文件。
- 应用专用密码:对于Gmail、Outlook等,使用应用专用密码而不是主密码。
- IMAP访问:确保邮箱已启用IMAP功能。
改进方向
- 使用配置文件存储邮箱信息。
- 添加邮件正文摘要提取。
- 支持多邮箱检查。
- 添加邮件过滤规则(只提醒重要发件人)。
这个脚本可以帮助你及时获取新邮件通知,适合需要在后台静默运行并提醒的场景。