如何修改含Base64编码内容的.eml邮件文件?寻求Python解决方案
问题解决方法与自动化脚本
为什么修改后Outlook不显示新内容?
- Outlook会缓存.eml文件,直接双击可能读取的是缓存,而非你修改后的文件。
- 多数.eml同时存储纯文本版和HTML版正文,你可能只修改了其中一个,Outlook默认显示未修改的版本。
- 替换的Base64编码未遵循MIME规则:编码内容必须每76个字符换一行,且与
Content-Transfer-Encoding行之间需保留空行。
手动修复步骤
- 绕开Outlook缓存:
关闭Outlook,找到路径C:\Users\<你的用户名>\AppData\Local\Microsoft\Outlook\RoamCache,删除其中的缓存文件。右键点击.eml文件,选择「打开方式」→「Outlook」,不要直接双击打开。 - 检查并修改所有正文版本:
用记事本打开.eml,搜索text/plain和text/html,每个标签下的Base64块都需检查。典型格式如下:
确保修改所有需要调整的内容块,修改后的Base64需分割为每76字符一行。Content-Type: text/html; charset="UTF-8" Content-Transfer-Encoding: base64 [Base64编码的HTML内容] - 核对编码格式:
编码内容与上方的Content-Transfer-Encoding行之间必须保留一个空行,结尾也不能有多余空行。
Python自动化脚本(一键修改)
用这个脚本可直接处理.eml文件,自动完成解码、修改、重新编码流程,无需手动使用在线工具:
import base64 import email import io def modify_eml_body(eml_path, output_path, modify_func, content_type='html'): # 读取原始邮件文件 with open(eml_path, 'rb') as f: msg = email.message_from_bytes(f.read()) # 遍历邮件所有内容块,定位待修改的正文 for part in msg.walk(): if part.is_multipart(): continue # 匹配目标内容类型(html或plain) if content_type in part.get_content_type(): # 解码Base64内容为字符串 decoded_text = part.get_payload(decode=True).decode('utf-8') # 应用自定义修改逻辑 modified_text = modify_func(decoded_text) # 重新编码为符合MIME规范的Base64(每76字符换行) encoded_data = base64.b64encode(modified_text.encode('utf-8')) encoded_text = encoded_data.decode('utf-8') encoded_text = '\n'.join([encoded_text[i:i+76] for i in range(0, len(encoded_text), 76)]) # 更新邮件内容 part.set_payload(encoded_text) # 保存修改后的邮件 with open(output_path, 'wb') as f: gen = email.generator.BytesGenerator(f) gen.flatten(msg) # ---------------------- 自定义修改规则 ---------------------- def clean_unwanted_text(text): # 替换为你需要删除的多余语句,支持同时删除多个 unwanted_lines = [ "这是要删除的多余语句1", "这是要删除的多余语句2" ] for line in unwanted_lines: text = text.replace(line, "") return text # ---------------------- 使用示例 ---------------------- if __name__ == "__main__": input_file = "待修改的邮件.eml" output_file = "修改完成的邮件.eml" # 修改HTML正文,若需修改纯文本,将content_type改为'plain' modify_eml_body(input_file, output_file, clean_unwanted_text, content_type='html') print(f"修改完成!文件已保存到 {output_file}")
使用说明
- 将
unwanted_lines中的内容替换为你要删除的多余语句,可添加多个目标内容。 - 如果邮件是纯文本格式(非HTML),将参数
content_type='html'改为content_type='plain'。 - 运行脚本后,右键选择「打开方式」→「Outlook」打开修改后的文件,避免缓存干扰。
内容的提问来源于stack exchange,提问作者Pita
相关产品推荐
相关产品推荐

