python自动从本地foxmail中获取某一主题的读取_用Python读取Foxmail导出的邮件
时间: 2024-02-28 20:54:32 浏览: 172
导出foxmail中的邮件
下面是一个示例代码,可以实现自动从本地Foxmail中获取某一主题的邮件:
```python
import os
import email
import codecs
def get_mail_by_subject(subject):
"""
根据主题获取邮件
"""
mail_dir = 'Foxmail邮件存储路径'
for root, dirs, files in os.walk(mail_dir):
for file_name in files:
if file_name.endswith('.eml'):
file_path = os.path.join(root, file_name)
with open(file_path, 'rb') as f:
content = f.read()
try:
msg = email.message_from_bytes(content)
if msg['Subject'] == subject:
return read_foxmail_eml(file_path)
except:
pass
def read_foxmail_eml(eml_path):
"""
读取Foxmail导出的.eml文件
"""
with open(eml_path, 'rb') as f:
content = f.read()
msg = email.message_from_bytes(content)
subject = msg['Subject']
from_address = msg['From']
to_address = msg['To']
date = msg['Date']
body = msg.get_payload(decode=True).decode()
# 处理HTML格式的正文
if msg.is_multipart():
for part in msg.walk():
content_type = part.get_content_type()
filename = part.get_filename()
if content_type == 'text/html':
body = part.get_payload(decode=True).decode()
else:
content_type = msg.get_content_type()
if content_type == 'text/html':
body = msg.get_payload(decode=True).decode()
# 处理附件
attachments = []
if msg.is_multipart():
for part in msg.walk():
content_type = part.get_content_type()
filename = part.get_filename()
if filename:
filename = decode_str(filename)
data = part.get_payload(decode=True)
attachment = {'filename': filename, 'data': data}
attachments.append(attachment)
result = {'from': from_address, 'to': to_address, 'subject': subject, 'date': date, 'body': body, 'attachments': attachments}
return result
def decode_str(s):
"""
解码字符串
"""
value, charset = email.header.decode_header(s)[0]
if charset:
value = value.decode(charset)
return value
if __name__ == '__main__':
# 测试代码
subject = '测试邮件主题'
result = get_mail_by_subject(subject)
print(result)
```
你只需要将 `mail_dir` 改为你本地Foxmail邮件存储路径,将 `subject` 改为你要查找的邮件主题,运行代码即可自动获取该主题的邮件内容。
阅读全文