如何使用 Python 在 Outlook 中提取邮件正文的一小部分?
How to extract small part of the email body in Outlook using Python?
我正在尝试自动从 outlook 中的标准邮件正文中提取信息。
我需要提取以下信息:
- 代码
- number1
- number3
然后将其传输到 excel 文件。
但现在我想知道如何在邮件正文中访问此信息。
这是标准邮件的示例:
Subject: Test1
Hi,
You got a new answer from user Alex.
Code: alex123fj
Number1: 0611111111
Number2: 1020
Number3: 3032
这是我的代码(我过滤了邮件以便我只能访问我在 1 天内收到的邮件):
import win32com.client
from datetime import datetime, timedelta
outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")
inbox = mapi.GetDefaultFolder(6)
messages = inbox.Items
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] = 'answers@gmail.com'")
messages = messages.Restrict("[Subject] = 'Test1'")
message = messages.GetLast()
body_content = message.body
使用正则表达式示例
https://regex101.com/r/b2t5iw/1
带有所选电子邮件的代码示例
import re
import win32com.client
def get_body(Item):
try:
print(Item.Subject)
body = Item.body
matches = re.finditer(r"Code:\s(.*)$", body, re.MULTILINE)
for match in matches:
print("Code: ", match.group(1))
except Exception as e:
print(e)
if __name__ == '__main__':
Outlook = win32com.client.Dispatch("Outlook.Application")
Items = Outlook.ActiveExplorer().Selection
Item = Items(1)
get_body(Item)
应该打印
Code: alex123fj
我正在尝试自动从 outlook 中的标准邮件正文中提取信息。 我需要提取以下信息:
- 代码
- number1
- number3
然后将其传输到 excel 文件。
但现在我想知道如何在邮件正文中访问此信息。
这是标准邮件的示例:
Subject: Test1
Hi,
You got a new answer from user Alex.
Code: alex123fj
Number1: 0611111111
Number2: 1020
Number3: 3032
这是我的代码(我过滤了邮件以便我只能访问我在 1 天内收到的邮件):
import win32com.client
from datetime import datetime, timedelta
outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")
inbox = mapi.GetDefaultFolder(6)
messages = inbox.Items
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] = 'answers@gmail.com'")
messages = messages.Restrict("[Subject] = 'Test1'")
message = messages.GetLast()
body_content = message.body
使用正则表达式示例
https://regex101.com/r/b2t5iw/1
带有所选电子邮件的代码示例
import re
import win32com.client
def get_body(Item):
try:
print(Item.Subject)
body = Item.body
matches = re.finditer(r"Code:\s(.*)$", body, re.MULTILINE)
for match in matches:
print("Code: ", match.group(1))
except Exception as e:
print(e)
if __name__ == '__main__':
Outlook = win32com.client.Dispatch("Outlook.Application")
Items = Outlook.ActiveExplorer().Selection
Item = Items(1)
get_body(Item)
应该打印
Code: alex123fj