编辑“ .eml”中的标题

时间:2018-12-14 17:56:34

标签: python-3.x email parsing email-headers

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

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

我正在寻找一种解析文件并更新标头内容的方法。

起初,我使用以下模块:

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

我能够发送正文的内容,但是当我尝试发送附件时,我不得不从base64解码,并将附件提取到一个文件夹中,然后发送所有内容。我不需要更改标题的内容

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

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

  • smtplib 发送电子邮件
  • 我尝试 mail-parser 未能成功更新内容中的任何内容,因为更新后的值不是永久性的,例如:

    mail = mailparser.parse_from_bytes(byte_mail) mail.from_ = [('我的名字','email@example.com')] print(mail.headers)#这将打印原始标题

我还尝试使用mail.update()和使用此模块的各种方法,但均未成功。

我找到了一条帖子Python: Modify Values in eml file (email header),该帖子建议使用 email 中的Parser,replace_header和as_string,但由于无法调用 replace_header 和 as_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”发送回特定地址。

1 个答案:

答案 0 :(得分:0)

该问题已通过使用 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()