我使用 Python 后端和 JS 前端为 sendgrid 设置了动态模板,一切都发送良好,但取消订阅不起作用。我做了一些挖掘,发现了一个类似的案例 SendGrid API Dynamic - can't get Unsubscribe to work 这会很棒,但它不是 Python。 Sendgrid 支持不想触及代码,甚至库和文档都让我很难找到一个 asm 取消订阅变量来传递组 ID。这是我当前的代码,在后端调用 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
这是官方的Python库https://github.com/sendgrid/sendgrid-python/tree/main我确实花了一天时间浏览这个库,但还没有找到任何东西。
我尝试查看文档,与 sendgrid 支持人员交谈,并查看库示例。
缺少取消订阅文档。添加:
message.asm = Asm(GroupId(XXXXX))
XXXXX 是 sendgrid 取消订阅组的 ID。您需要确保还从 sendgrid.helpers.mail 导入 Asm 和 GroupId
from sendgrid.helpers.mail import Asm, GroupId
请注意,您还需要编辑动态模板的 html 以删除“取消订阅”链接,并且只有“取消订阅首选项”链接(基本上使其成为两步取消订阅方法)。否则,大多数电子邮件客户端会点击检查并自动取消订阅。