在".eml"中编辑标题



作为一个简短的总结,我在一个目录中有一堆'.eml'文件。我需要将这些电子邮件转发回email@example.com"。

问题是".eml"文件头中的字段"发件人"包含另一个与"不匹配的电子邮件地址email@example.com"。

我已经找到了一种解析文件和更新头内容的方法。

起初,我使用以下模块:

  • eml.parser解析文件
  • pyo365连接到MSGraph API

我可以发送正文的内容,但当我尝试发送附件时,我必须从base64解码并提取文件夹中的附件,然后发送所有内容。我不需要更改页眉的内容

我知道这是一个糟糕的举动,因为可能有一种方法可以发送编码的附件。

此外,由于MSGraph附件的文件大小限制为每次请求4mb,我决定尝试更改为:

  • smtplib发送电子邮件
  • 我尝试了邮件解析器,但没有成功更新内容中的任何内容,因为更新的值不会是永久的,例如:

    mail=mailparser.parse_from_bytes(byt_mail(mail.from _=[('我的名字','email@example.com'(]print(mail.headers(#这将打印原始标头

我还尝试了mail.update((和使用该模块的各种方法,但都没有成功。

我在eml文件(电子邮件头(中发现了一个Python:Modify Values的帖子,建议使用电子邮件中的Parser、replace_header和as_string,但我也无法使其工作,因为我无法调用replace_headas_string

from email.message import EmailMessage #contains as_string
from email.parser import HeaderParser
file = open(filename, 'r')
h = HeaderParser().parse(file)
#stuck here

我知道这可能不仅仅是一个问题,主要目标是将eml文件发送回特定地址,从email@example.com"。

通过使用eml_parser解析电子邮件解决了此问题。我创建了自己的标题,附加了HTML正文内容和附件。

from passlib.context import CryptContext
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.header import Header
def send(self, dst):
try:
self.m = MIMEMultipart()
self.m['From'] = self.client_addr
self.m['To'] = dst
# Must have Header() in python 3.x otherwise you get UnicodeError
self.m['Subject'] = Header(self.get_subject(),  'utf-8')
#Attach HTML body with the right encoding
self.m.attach(MIMEText(self.get_body().encode('utf-8'), 'html', 'utf-8'))
# Extract attachments to self.attachment_path
self.extract_attachments(self.parsed_eml)
server = smtplib.SMTP('smtp.office365.com', 587)
server.ehlo()
server.starttls()
# Compare hash in config.json file
if self.pwd_context.verify(self.client_plain_secret, self.client_secret):
server.login(self.client_addr, self.client_plain_secret)
server.sendmail(self.m['From'], self.m['To'], self.m.as_string())
server.quit()
except:
print("An error occured trying to send the email.")
finally:
self.clean_attachments()

最新更新