如何在发送至Gmail的Prometheus邮件告警中正确显示换行符?
I’ve run into this exact headache before—Gmail renders alert emails as HTML, so plain \n newlines don’t get parsed as line breaks, and raw <br> tags often get escaped by Alertmanager’s default templates. Here’s how to fix it:
Root Cause
Prometheus passes annotation text to Alertmanager, which uses a default email template that escapes HTML by default. That’s why your \n shows up as literal text, and <br> gets converted to <br> instead of rendering a line break.
Solution 1: Modify Alertmanager’s Email Template
This is the most reliable fix. Update your Alertmanager template to convert newlines to HTML breaks and mark the content as safe for rendering:
- Locate your Alertmanager template file (usually named
template.htmlor embedded in your Alertmanager config). - Find the section where annotations are rendered, and adjust the
descriptionline to use these template filters:<p>{{ .Annotations.description | replace "\n" "<br>" | safeHTML }}</p> - Save the template and restart Alertmanager.
Now you can keep using \n in your alert rules like you originally did:
alert: KubernetesPodImagePullBackOff expr: kube_pod_container_status_waiting_reason{reason=~"ContainerCreating|CrashLoopBackOff|ErrImagePull|ImagePullBackOff"} > 0 for: 1s labels: severity: warning annotations: summary: "Kubernetes pod crash looping (instance {{ $labels.instance }})" description: "Pod {{ $labels.pod }} is crash looping\n VALUE = {{ $value }}\n LABELS: {{ $labels }}"
Solution 2: Use HTML Breaks Directly in Annotations
If you prefer writing <br> directly in your annotations, you need to ensure Alertmanager doesn’t escape them:
- Update your alert rule annotations with
<br>and use YAML’s block scalar (|) for readability:annotations: summary: "Kubernetes pod crash looping (instance {{ $labels.instance }})" description: | Pod {{ $labels.pod }} is crash looping<br> VALUE = {{ $value }}<br> LABELS: {{ $labels }} - Add the
safeHTMLfilter to your Alertmanager template’s description rendering (same as Solution 1) to prevent tag escaping.
Solution 3: Use Prometheus Template Functions (No Template Changes)
If you can’t modify the Alertmanager template, use Prometheus’s replace function directly in your annotations to swap \n for <br>—just make sure to escape backslashes properly in YAML:
annotations: description: '{{ replace "Pod {{ $labels.pod }} is crash looping\n VALUE = {{ $value }}\n LABELS: {{ $labels }}" "\n" "<br>" }}'
The extra quotes and escaping tell Prometheus to process the replacement before sending the text to Alertmanager.
Testing
After making changes, trigger a test alert (you can use amtool for this) to verify line breaks show up correctly in Gmail.
内容的提问来源于stack exchange,提问作者user630702

