【问题标题】:How to print email body from outlook without signature - Python如何在没有签名的情况下从 Outlook 打印电子邮件正文 - Python
【发布时间】:2021-07-02 21:52:40
【问题描述】:

我正在尝试解析来自 Outlook 的电子邮件。 我想打印以下内容:

  • 主题
  • 正文(不包括发件人签名)
  • 忽略之前所有来自转换的电子邮件(回复和转发)

有什么方法可以在行间多空格之前打印出正文(通常这是签名与正文分开的方式)?

任何帮助将不胜感激!

import win32com.client
#other libraries to be used in this script
import os
from datetime import datetime, timedelta


outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")

 
for account in mapi.Accounts:
    print(account.DeliveryStore.DisplayName) 
    
    
inbox = mapi.GetDefaultFolder(6)


messages = inbox.Items
messages.Sort('[ReceivedTime]', True)
received_dt = datetime.now() - timedelta(days=1)
received_dt = received_dt.strftime('%m/%d/%Y %H:%M %p')
messages = messages.Restrict("[ReceivedTime] >= '" + received_dt + "'")
messages = messages.Restrict("[SenderEmailAddress] = 'firstname.lastname@gmail.com'")
message = messages.GetFirst()

print ("Current date/time: "+ received_dt)
while message:
    print(message.Subject)
    print(message.body)
    message = messages.GetNext ()

【问题讨论】:

    标签: python email-parsing


    【解决方案1】:

    您可以使用正则表达式忽略三个换行符之后的所有内容(段落之间通常有一两个换行符):

    import re
    
    r = re.compile(r"(.*)\n\n\n", re.MULTILINE + re.DOTALL)
    
    # ...
    
    while message:
        # ...
        match = r.match(message.body)
        if match:
            body_without_signature = r.match(message.body).groups(0)
        else:
            # No signature found
            body_without_signature = message.body
        print(body_without_signature)
    

    【讨论】:

    • 感谢您的回答。目前,它似乎找不到任何匹配项,因此它返回:“AttributeError: 'NoneType' object has no attribute 'groups'”。我将继续研究 RegEx,因为它似乎是满足我需求的最可行的解决方案。再次感谢
    • 是的,我的示例假定始终存在签名。请参阅我的更新答案以进行简单检查。
    猜你喜欢
    • 2013-08-30
    • 2017-06-01
    • 1970-01-01
    • 2015-12-12
    • 2020-05-19
    • 1970-01-01
    • 2013-02-11
    • 2020-09-13
    • 1970-01-01
    相关资源
    最近更新 更多