python识别outlook邮件并且将pdf文件作为附件发送邮件

为了发送 PDF 文件作为附件,可以在代码的邮件发送部分添加附件功能。以下是更新后的代码,展示如何将 PDF 文件作为附件发送。

修改后的代码

python 复制代码
import win32com.client
import pythoncom
import os

class OutlookEventHandler:
    def __init__(self, specified_email, pdf_path):
        self.specified_email = specified_email
        self.pdf_path = pdf_path
        self.outlook = win32com.client.DispatchWithEvents(
            "Outlook.Application", EventSink
        )
        EventSink.specified_email = specified_email
        EventSink.pdf_path = pdf_path
        EventSink.outlook = self.outlook

class EventSink:
    specified_email = None
    pdf_path = None
    outlook = None

    def OnNewMailEx(self, EntryIDCollection):
        """
        This event is triggered whenever a new email is received.
        """
        namespace = self.outlook.GetNamespace("MAPI")
        for entry_id in EntryIDCollection.split(","):
            mail_item = namespace.GetItemFromID(entry_id)
            if mail_item.Class == 43:  # Check if it's an email item
                self.process_email(mail_item)

    def process_email(self, mail_item):
        """
        Process the received email and send a new email with a PDF attachment.
        """
        subject = mail_item.Subject
        sender = mail_item.SenderEmailAddress
        body = mail_item.Body

        # Example check logic (you can customize this)
        if "urgent" in subject.lower():
            self.send_email(sender, subject)

    def send_email(self, sender, subject):
        """
        Send a new email to the specified address with a PDF attachment.
        """
        mail = self.outlook.CreateItem(0)  # 0: olMailItem
        mail.To = self.specified_email
        mail.Subject = f"Notification: Email from {sender}"
        mail.Body = f"Received an email with subject: {subject}"

        # Add PDF attachment
        if os.path.exists(self.pdf_path):
            mail.Attachments.Add(self.pdf_path)
        else:
            print(f"Attachment file not found: {self.pdf_path}")

        mail.Send()
        print(f"Notification with attachment sent to {self.specified_email}.")

if __name__ == "__main__":
    SPECIFIED_EMAIL = "example@domain.com"
    PDF_PATH = "C:\\path\\to\\your\\file.pdf"  # Update this to your PDF file path

    if not os.path.exists(PDF_PATH):
        print(f"Error: PDF file not found at {PDF_PATH}")
    else:
        print(f"Listening for new emails. Notifications with attachment will be sent to {SPECIFIED_EMAIL}.")
        event_handler = OutlookEventHandler(SPECIFIED_EMAIL, PDF_PATH)

        # Keep the script running to listen for new emails
        pythoncom.PumpMessages()

关键变化

  1. 附件路径
    • 在初始化时传入 PDF 文件的路径。
    • 确保路径合法且文件存在,使用 os.path.exists() 进行验证。
  2. 添加附件
    • 使用 mail.Attachments.Add(self.pdf_path) 添加附件。
    • 在发送邮件前,检查附件路径是否有效。

注意事项

  1. 附件大小:Outlook 邮件附件大小有限制,确保 PDF 文件符合限制。
  2. 文件路径:使用绝对路径,避免路径解析问题。
  3. 多附件支持 :如果需要添加多个附件,可以多次调用 mail.Attachments.Add(),传入不同的文件路径。
相关推荐
鸡鸭扣1 小时前
Docker:3、在VSCode上安装并运行python程序或JavaScript程序
运维·vscode·python·docker·容器·js
paterWang1 小时前
基于 Python 和 OpenCV 的酒店客房入侵检测系统设计与实现
开发语言·python·opencv
东方佑1 小时前
使用Python和OpenCV实现图像像素压缩与解压
开发语言·python·opencv
神秘_博士2 小时前
自制AirTag,支持安卓/鸿蒙/PC/Home Assistant,无需拥有iPhone
arm开发·python·物联网·flutter·docker·gitee
牵牛老人2 小时前
Qt中使用QPdfWriter类结合QPainter类绘制并输出PDF文件
数据库·qt·pdf
Moutai码农3 小时前
机器学习-生命周期
人工智能·python·机器学习·数据挖掘
小白教程4 小时前
python学习笔记,python处理 Excel、Word、PPT 以及邮件自动化办公
python·python学习·python安装
武陵悭臾4 小时前
网络爬虫学习:借助DeepSeek完善爬虫软件,实现模拟鼠标右键点击,将链接另存为本地文件
python·selenium·网络爬虫·pyautogui·deepseek·鼠标右键模拟·保存链接为htm
代码猪猪傻瓜coding5 小时前
关于 形状信息提取的说明
人工智能·python·深度学习
码界筑梦坊6 小时前
基于Flask的第七次人口普查数据分析系统的设计与实现
后端·python·信息可视化·flask·毕业设计