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

Python SendGrid:如何在HTML邮件内容中正确拼接字符串

解决Python SendGrid邮件中插入字符串变量的问题

你的问题出在没有正确在HTML字符串中解析变量str1,直接写+ str1会被当成普通文本显示,而不是替换成变量的值。下面是几种可行的修复方式:

方法1:使用f-string(推荐,Python3.6+支持)

在三引号字符串前加f,然后用{str1}作为变量占位符:

str1 = 'StringToBeAdded'
html_content1 = f''' Hi All,
        <br>
        <br>
        Greetings from xyz!
        <br>
        Attached is the report of your data - {str1}
        <br>
        <br>
        Note: This is an automated email. In case of any queries, please reach us at 
        <br>
        Regards,
        <br>
        abc '''
# 修正原代码的语法错误:to_emails和subject的引号要闭合
message = Mail(
    from_email='from@example.com',
    to_emails='to@example.com',
    subject='Mail',
    html_content=html_content1)

方法2:使用str.format()方法

把变量位置换成占位符,再调用format传入变量:

str1 = 'StringToBeAdded'
html_content1 = ''' Hi All,
        <br>
        <br>
        Greetings from xyz!
        <br>
        Attached is the report of your data - {}
        <br>
        <br>
        Note: This is an automated email. In case of any queries, please reach us at 
        <br>
        Regards,
        <br>
        abc '''.format(str1)
message = Mail(
    from_email='from@example.com',
    to_emails='to@example.com',
    subject='Mail',
    html_content=html_content1)

方法3:字符串拼接

把HTML内容拆分成多段,用+连接变量:

str1 = 'StringToBeAdded'
html_content1 = ''' Hi All,
        <br>
        <br>
        Greetings from xyz!
        <br>
        Attached is the report of your data - ''' + str1 + '''
        <br>
        <br>
        Note: This is an automated email. In case of any queries, please reach us at 
        <br>
        Regards,
        <br>
        abc '''
message = Mail(
    from_email='from@example.com',
    to_emails='to@example.com',
    subject='Mail',
    html_content=html_content1)

另外注意原代码里的两处语法错误:to_emails=to@example.com'少了开头的单引号,subject='Mail,少了结尾的单引号,这些都要修正才能正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 02:35:13