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

使用Python调用Mailchimp API发送带附件邮件未携带附件问题

问题原因

你的代码参数层级传递错误:attachments是message消息体的内部字段,不属于和template_name、message平级的顶级请求参数。你将附件配置放在请求最外层时,接口不会识别该字段,因此发送的邮件不会携带附件。

修复方案

调整参数结构,将附件配置移入message对象内部即可,修正后的参考代码如下:

import base64

# 读取并编码附件,这部分你的原有逻辑是正确的
with open('file.pdf','rb') as f:
    file_data = f.read()
    encoded_data = base64.b64encode(file_data).decode('utf-8')

# 构造消息体,将attachments作为msg的属性传入
msg = {
    # 此处保留你原有msg配置中的所有字段,比如发件人、收件人、主题、合并变量等
    "from_email": "你的发件邮箱",
    "subject": "邮件主题",
    "to": [{"email": "收件人邮箱", "type": "to"}],
    # 附件配置放在message内部
    "attachments": [
        {
            "content": encoded_data,
            "name": "file.pdf",
            "type": "application/pdf"
        }
    ]
}

# 发送请求时移除顶级参数里的attachments
try:
    response = mailchimp.messages.send_template({
        "template_name": template,
        "template_content": [],
        "message": msg
    })
    print(response)
except Exception as e:
    print(f"发送失败: {e}")
校验注意事项
  • 单封邮件的所有附件总大小不能超过25MB,超出限制时接口会自动丢弃附件配置
  • 附件的type字段需填写和文件格式匹配的MIME类型,PDF对应application/pdf的配置是正确的,其他格式需替换为对应值
  • 如果你的模板中配置了动态内容块,确认没有逻辑覆盖message对象内的附件字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 17:21:10