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

SendGrid动态模板退订功能失效问题求助(Python后端)

SendGrid动态模板退订功能失效(Python后端)

我通过Python后端配合JS前端配置了SendGrid动态模板,邮件发送正常,但退订功能无法使用。找到过类似问题的解决方案,但都是非Python版本;咨询SendGrid支持后对方不提供代码协助,在官方Python库及文档里也很难找到传递退订组ID的ASM变量的方法。

当前后端API调用代码如下:

def send_emails(recipient_emails, template_id):
    sg = SendGridAPIClient(api_key=sendgrid_key)
    for recipient_email in recipient_emails:
        print("Sending email to:", recipient_email)
        message = Mail(
            from_email="info@info",
            to_emails=recipient_email,
        )
        message.template_id = template_id
        try:
            response = sg.send(message)
            print(f"Email sent to {recipient_email} - Status Code: {response.status_code}")
        except Exception as e:
            print(f"Failed to send email to {recipient_email}: {str(e)}")
        time.sleep(1)  # Wait for one second before sending the next email

解决方法:添加ASM退订组ID配置

SendGrid的退订功能依赖ASM(Advanced Suppression Manager)配置,需在邮件对象中指定asm参数传入退订组ID。Python库中可通过message.asm属性设置,具体操作如下:

  1. 先在SendGrid后台创建退订组,获取对应的group_id(路径:Marketing > Suppressions > Unsubscribe Groups)
  2. 在邮件对象中添加ASM配置:

修改后的完整代码:

def send_emails(recipient_emails, template_id):
    sg = SendGridAPIClient(api_key=sendgrid_key)
    # 替换为你的退订组ID
    unsubscribe_group_id = 123456
    for recipient_email in recipient_emails:
        print("Sending email to:", recipient_email)
        message = Mail(
            from_email="info@info",
            to_emails=recipient_email,
        )
        message.template_id = template_id
        # 配置ASM退订组
        message.asm = {"group_id": unsubscribe_group_id}
        try:
            response = sg.send(message)
            print(f"Email sent to {recipient_email} - Status Code: {response.status_code}")
        except Exception as e:
            print(f"Failed to send email to {recipient_email}: {str(e)}")
        time.sleep(1)  # Wait for one second before sending the next email

额外说明

  • 确保动态模板中已正确插入SendGrid官方的退订链接(模板编辑时选择添加「Unsubscribe」组件)
  • 若需支持多组退订,可扩展asm参数,指定显示给用户的退订组列表:
    message.asm = {
        "group_id": 123456,
        "groups_to_display": [123456, 789012]
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 22:05:04