You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用SendGrid发邮件时如何在邮件正文中插入动态变量值

实现方案

要在html_content参数中插入动态变化的变量值,直接使用Python内置的字符串格式化功能即可,优先推荐使用Python 3.6+版本支持的f-string语法,写法简单易读。

修改后的完整代码

variance_count_gw = 3100
duplicate_count_gw = 200

# 若variance_count大于3000或duplicate_count大于1000,则触发邮件发送
import os, requests, urllib, json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

message = Mail(
    from_email='a@xyz.com',
    to_emails=['b@ght.com'],
    subject='Variance/Duplicate count status',
    # 字符串前加f即可用{}插入变量,可根据需求自定义HTML排版
    html_content=f'<strong>方差计数:{variance_count_gw},重复计数:{duplicate_count_gw}</strong>'
)

sg = SendGridAPIClient('value') 

if variance_count_gw > 3000 or duplicate_count_gw > 1000 :
      sg.send(message)

其他可选格式化方案

如果使用的Python版本低于3.6,可替换为以下两种写法:

  • str.format写法:
html_content='<strong>方差计数:{},重复计数:{}</strong>'.format(variance_count_gw, duplicate_count_gw)
  • %格式化写法:
html_content='<strong>方差计数:%d,重复计数:%d</strong>' % (variance_count_gw, duplicate_count_gw)

如果需要调整数值的展示格式,比如增加千位分隔符,直接在f-string的变量后加格式声明即可,示例:{variance_count_gw:,} 输出为3,100。

内容的提问来源于stack exchange,提问作者Saswat Ray

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 23:45:02