python读取本地foxmail举例实际案例代码
时间: 2023-07-03 19:27:25 浏览: 171
以下是一个读取本地Foxmail导出邮件的实际案例代码:
```python
import os
import email
import codecs
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__':
# 测试代码
eml_path = 'test.eml'
result = read_foxmail_eml(eml_path)
print(result)
```
这个代码可以读取指定路径下的.eml文件,并解析邮件内容,包括发件人、收件人、主题、日期、正文和附件等信息。你只需要将 `eml_path` 改为你的.eml文件路径即可。
阅读全文