如何发送一个漂亮的json对象作为电子邮件python

ana*_*cky 3 python email json elasticsearch

我有一个 python 脚本,它以 json 形式获取集群运行状况并向我发送邮件。问题是 json 没有很好地打印出来。这些是我已经尝试过的方法:

  1. 简单 --> json.dumps(health)
  2. json.dumps(health, indent=4, sort_keys=True)

但是gmail中的输出还是没有格式化的,有点像这样

{ "active_primary_shards": 25, "active_shards": 50, "active_shards_percent_as_number": 100.0, "cluster_name": "number_of_pending_tasks": 0, "relocating_shards": 0, "status": "green", "task_max_waiting_in_queue_millis": 0, "timed_out": false, "unassigned_shards": 0 }

邮件已发送至 gmail

Pro*_*les 5

我不能肯定地说,但似乎您的电子邮件发送代码默认发送“HTML”电子邮件,并且在 HTML 中连续空格折叠为一个,这样 HTML 代码如下:

<p>
    This is a paragraph, but it's long so
    I'll break to a new line, and indented
    so I know it's within the `p` tag, etc.
</p>
Run Code Online (Sandbox Code Playgroud)

看起来像“这是一个段落,但它很长,所以我会换到一个新行,并缩进所以我知道它在p标签内,等等。” 给用户。

所以,我想说你的两个选择是:

  1. 更改电子邮件发送代码以将Content-type标题发送为text/plain,或
  2. &nbsp;(不间断空格)字符替换所有空格,用<br>(中断)替换换行符,例如:

    email_body = json.dumps(
        health, indent=4, sort_keys=True).replace(' ', '&nbsp;').replace('\n', '<br>')
    
    Run Code Online (Sandbox Code Playgroud)