简体   繁体   English

在Python中通过smtplib发送的电子邮件中附加Json文件

[英]attach Json file in email send through smtplib in Python

I have a json file, and want to attach that JSON file in email send by smtplib in Python. 我有一个json文件,并希望将该JSON文件附加到Python中smtplib发送的电子邮件中。 But when I open the attachment in email, it can not be correctly parsed as JSON, I believe that there must be some special character there. 但是,当我在电子邮件中打开附件时,无法将其正确解析为JSON,我相信那里必须有一些特殊字符。

Here is the code I used 这是我使用的代码

    sub = "debugging tool results for request_id=" + requestid
    msg = MIMEMultipart('alternative')
    msg['From'] = 'no-reply@localhost.com'
    msg['To'] = 'destination@abc.com'
    msg['Subject'] = sub
    #msg['Content-Type'] = "application/json; charset=utf-8"

    text = "please find the debugging result from attachment"
    part1 = MIMEText(text, 'plain')

    msg.attach(part1)

    filename = "/app/" + requestid + ".json"
    with open(filename) as data_file:
        data = json.load(data_file)
    print json.dumps(data)  # I tried to print here, and the output looks good, valid json.

    f = codecs.open(filename, "r", "utf-8")
    # f = file(filename)   
    attachment = MIMEText(f.read())
    attachment.add_header('Content-Disposition', 'attachment', filename=filename)
    msg.attach(attachment)


    s = smtplib.SMTP()
    s.connect()
    s.sendmail('no-reply@localhost.com', 'destination@abc.com', msg.as_string())
    s.quit()

I know the reason why it is invalid JSON, since in the attachment JSON file, several newline symbol has been added, when I manually deleted them, it worked, how to avoid that newline character being added ? 我知道为什么它是无效的JSON的原因,因为在附件JSON文件中,添加了几个换行符,当我手动删除它们时,它起作用了,如何避免添加换行符? If there any specific attachment handling for json file ? 是否对json文件进行任何特定的附件处理?

I finally got this issue solved. 我终于解决了这个问题。 It is about the charset, add following 关于字符集,添加以下内容

   msg.set_charset('utf-8')
   attachment = MIMEText(f.read().rstrip("\n"), 'plain', 'utf-8')

Make it as utf-8 encoding schema. 将其设置为utf-8编码架构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM