我有一个json文件,并希望将该JSON文件附加到smtplib在Python中发送的电子邮件中。但是当我在电子邮件中打开附件时,它无法正确解析为JSON,我相信必须有一些特殊的字符。
这是我使用的代码
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()
我知道它是无效JSON的原因,因为在附件JSON文件中添加了几个换行符号,当我手动删除它们时,它有效,如何避免添加换行符?如果json文件有任何特定的附件处理?
答案 0 :(得分:0)
我终于解决了这个问题。它是关于charset,添加以下
android:inputType="text|textMultiLine"
将其设为utf-8编码架构。