Skip to main content
 首页 » 编程设计

Python:修改 eml 文件中的值(电子邮件 header )

2025年04月02日34pander-it

我想使用 Python 更改“收件人”和“发件人”字段的电子邮件地址。到目前为止,我做了以下工作以阅读必填字段。任何人请建议,如何改变它们。

from email.parser import Parser 
 
fp = open('2.eml', 'r+') 
headers = Parser().parse(fp) 
 
# Make changes only within a code, Not in to the file. I would like to save given changes for from in to my 2.eml file 
headers.replace_header('from', 'newEmail@domain.com')  
 
print ('To: %s' % headers['to']) 
print ('From: %s' % headers['from']) 
print ('Subject: %s' % headers['subject']) 

请您参考如下方法:

您应该将更改后的消息写回文件:

with open('2.eml', 'w') as outfile: 
    outfile.write(headers.as_string()) 

请注意,您的名称 headers 并不完全准确,因为 email.parser.Parser.parse 返回的值是email.message.Message .