I have a json file, and want to attach that JSON file in email send by smtplib in Python. 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.
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 ? If there any specific attachment handling for json file ?