0

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 ?

Terry
  • 855
  • 4
  • 12
  • 16
  • 1
    I'm not exactly well-versed in this, but I'd immediately try opening the file as binary (`f = codecs.open(filename, 'rb')`) and see if that doesn't fix it. Lots of generic "extra newlines" errors are caused by reading `\r\n` into `\n` and vice versa that's caused by opening as text what should be binary. – Adam Smith Oct 12 '15 at 22:59
  • Thanks Adam, but I tried and it did not work. I even tried to use this attachment = MIMEText(f.read().rstrip("\n")) or attachment = MIMEText(f.read().rstrip()), and no luck. – Terry Oct 12 '15 at 23:25

1 Answers1

0

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.

Terry
  • 855
  • 4
  • 12
  • 16