Python pywin32 outlook邮箱

Python pywin32 outlook邮箱

安装依赖

sh 复制代码
pip install pywin32

使用实例

python 复制代码
outlook = client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)  # 6表示收件箱

# 创建时间范围过滤器
end_time = dt.now()
start_time = end_time - timedelta(days=3)
# Restrict()过滤时间格式 %Y-%m-%d %H:%M %p必须带有%p,否则可能报错,或者没数据
start_str = start_time.strftime("%Y-%m-%d %H:%M %p")   
end_str = end_time.strftime("%Y-%m-%d %H:%M %p")
filter_str = f"[ReceivedTime] > '{start_str}' AND [ReceivedTime] < '{end_str}'"
# 通过时间过滤邮件
emails= inbox.Items.Restrict(filter_str)

for email in emails:
    # 邮件标题
    print(email.Subject)
    # 发送人
    print(email.SenderName)
    # 邮件内容(HTML格式)
    print(email.HTMLBody)
    # 邮件接收时间
    print(email.ReceivedTime)
    # 文件对象,包括附件,邮件中截图,图片等文件
    print(email.Attachments)
    # 邮件收件人(包括抄送人)信息对象
    for i in message.Recipients:
        print(i.Name)      # 收件人名称
        print(i.Resolved)	 # 
        print(i.Address)	# 收件人邮箱地址
        print(i.Type)     # 1:收件人,2:抄送人

    # 附件对象
    for attachment in email.Attachments:
        # attachment.FileName 文件名
        filename = str(attachment.FileName)
        suffix = os.path.splitext(filename)[1].strip(".")
        if filename.startswith('image') and suffix in ["png", "jpg"]: continue
        print(filename)
        dir_path = r'D:\test'
        filepath = os.path.join(dir_path, attachment.FileName)
        # attachment.SaveAsFile()保存文件到指定路径
        attachment.SaveAsFile(filepath)
相关推荐
小九九的爸爸1 小时前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学2 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田18 小时前
Pydantic校验配置文件
python
hboot18 小时前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi1 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽1 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187911 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅2 天前
海天线算法的前世今生
python·计算机视觉