如何在Python中将.msg文件转换为.eml文件(支持内存转换)
.msg转.eml内存内转换可行方案
针对你的需求,以下几个工具/方法可以实现纯内存内的.msg到.eml转换,无需落地文件:
1. msg-parser + Python内置email模块(跨平台)
msg-parser能完整解析.msg文件的结构,结合Python标准库的email模块可以手动构建.eml格式的邮件对象,最终生成内存字节流。
安装依赖
pip install msg-parser
实现代码
from msg_parser import MsOxMessage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders import io def msg_to_eml_in_memory(msg_bytes): # 从内存字节流解析.msg文件 msg = MsOxMessage(io.BytesIO(msg_bytes)) # 构建.eml对应的MIME对象 eml_msg = MIMEMultipart() eml_msg['From'] = msg.sender eml_msg['To'] = ', '.join(msg.to) eml_msg['Subject'] = msg.subject eml_msg['Date'] = msg.date.strftime('%a, %d %b %Y %H:%M:%S %z') # 添加纯文本/HTML正文 if msg.body: eml_msg.attach(MIMEText(msg.body, 'plain')) if msg.html_body: eml_msg.attach(MIMEText(msg.html_body, 'html')) # 处理附件 for attachment in msg.attachments: part = MIMEBase('application', 'octet-stream') part.set_payload(attachment.data) encoders.encode_base64(part) part.add_header('Content-Disposition', f'attachment; filename="{attachment.name}"') eml_msg.attach(part) # 生成内存中的.eml字节流 return eml_msg.as_bytes() # 使用示例:msg_bytes为用户上传的.msg文件原始字节 # eml_data = msg_to_eml_in_memory(msg_bytes)
2. pywin32(Windows专属,依赖Outlook)
如果你的API部署在Windows环境,可以利用pywin32调用Outlook的COM接口,直接在内存中完成转换,这种方式对复杂.msg的兼容性最好(比如内嵌邮件、特殊格式内容)。
安装依赖
pip install pywin32
实现代码
import win32com.client import io import win32com.server.util import win32com.stream def msg_to_eml_win_in_memory(msg_bytes): # 将内存字节转换为COM可识别的IStream对象 hglobal = win32com.server.util.HGlobalFromBytes(msg_bytes) stream = win32com.stream.CreateStreamOnHGlobal(hglobal, True) # 调用Outlook接口打开.msg并保存为.eml outlook = win32com.client.Dispatch("Outlook.Application") msg = outlook.Session.OpenSharedItem(stream) eml_stream = io.BytesIO() # olEML对应枚举值10,指定保存为.eml格式 msg.SaveAs(eml_stream, 10) msg.Close(0) # 0表示不保存修改直接关闭 eml_stream.seek(0) return eml_stream.read()
3. pylibmsg(跨平台,高性能)
pylibmsg是libmsg库的Python绑定,专门用于解析.msg文件,支持直接生成.eml格式的字节流,无需手动构建MIME结构,适合处理复杂或大体积的.msg文件。
安装依赖
pip install pylibmsg
实现代码
import pylibmsg import io def msg_to_eml_libmsg(msg_bytes): # 从内存字节流加载.msg并直接转换为.eml msg = pylibmsg.Message(io.BytesIO(msg_bytes)) return msg.to_eml()
注意事项
- 优先测试转换后的.eml是否能被第三方SaaS正常解析,重点验证特殊场景:非ASCII字符、内嵌图片、超大附件、嵌套邮件等。
- 处理大文件时,注意监控内存占用,必要时可结合流式处理优化。
内容的提问来源于stack exchange,提问作者giacom0c
相关产品推荐
相关产品推荐

