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

Django Anymail配置双Mailgun发件域名时401授权错误排查与解决

错误原因及解决方案

错误原因

  1. Anymail Mailgun后端不支持通过esp_extra传递api_key:esp_extra仅用于传递Mailgun API接收的额外请求参数,而API密钥是Anymail与Mailgun服务做身份认证的专属配置项,不属于Mailgun API请求体的一部分。你的代码中,即便在esp_extra里指定了domain2的API密钥,Anymail仍会使用settings里默认的API_KEY_DOMAIN1发起请求,用domain1的密钥访问domain2的发件域名接口,必然触发401权限验证失败。
  2. 你的settings配置存在语法错误:'MAILGUN_SENDER_DOMAIN': SENDER_DOMAIN_1'], 多了一个右方括号,虽然你说单独配置时正常,但建议修正以避免潜在问题。

解决方案

正确的做法是针对不同域名创建独立的Mailgun邮件连接,通过实例化MailgunBackend来指定对应域名的API密钥和发件域名,而非通过esp_extra传递。

修改后的发送代码示例

from anymail.backends.mailgun import MailgunBackend

# 构建邮件对象(逻辑与原代码一致)
email = AnymailMessage(
    to=message.to.split(','),
    cc=message.cc.split(',') if message.cc else None,
    bcc=message.bcc.split(',') if message.bcc else None,
    reply_to=None,
    subject=message.notification.subject,
    body=message.notification.body_text,
    from_email=message.from_email,
)
email.attach_alternative(message.notification.body_html, 'text/html')

# 根据用户品牌切换邮件连接
if user.brand['name'] == 'domain2':
    # 创建domain2对应的Mailgun连接
    custom_connection = MailgunBackend(
        api_key=API_KEY_DOMAIN2,
        sender_domain=SENDER_DOMAIN_2
    )
    # 为当前邮件对象指定该连接
    email.connection = custom_connection

try:
    email.send()
except Exception as e:
    print('Error sending email:', e)

额外注意事项

  • 确保from_email与对应的sender_domain匹配:noreply@domain2.com必须对应mg.domain2.com,Mailgun会验证发件邮箱的域名归属。
  • 若需频繁切换域名,可封装工具函数,根据品牌名称返回对应的Mailgun连接,减少重复代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 05:35:11