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

SendGrid Python发送含特殊字符收件人邮件触发KeyError问题求助

SendGrid Python SDK处理含特殊字符邮箱时触发KeyError问题

使用SendGrid Python官方PyPI提供的代码发送邮件,当收件人邮箱包含“(”这类特殊字符时,出现如下KeyError错误,此前代码可正常运行,询问是否有其他用户遇到同类情况。

用于发送邮件的代码

import requests
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import From, Mail, To

import config


def send_mail(
    template_id: str,
    subject: str,
    from_name: str,
    to_email: str,
) -> requests.Response:
    message = Mail(
        from_email=From(config.TEAM_EMAIL, from_name), to_emails=To(to_email)
    )
    message.template_id = template_id
    sg = SendGridAPIClient(config.SENDGRID_API_KEY)
    response = sg.send(message)
    print_sendgrid_response(response)
    return response

触发的错误栈

sendgrid\base_interface.py", line 60, in send
    message = message.get()
              ^^^^^^^^^^^^^
sendgrid\helpers\mail\mail.py", line 969, in get
    'personalizations': [p.get() for p in self.personalizations or []],
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
sendgrid\helpers\mail\mail.py", line 969, in <listcomp>
    'personalizations': [p.get() for p in self.personalizations or []],
                         ^^^^^^^
sendgrid\helpers\mail\personalization.py", line 250, in get
    value = getattr(self, key)
            ^^^^^^^^^^^^^^^^^^
sendgrid\helpers\mail\personalization.py", line 55, in tos
    return self._get_unique_recipients(self._tos)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
sendgrid\helpers\mail\personalization.py", line 39, in _get_unique_recipients
    recipient_email = recipient['email'].lower() if isinstance(recipient, dict) else recipient.email.lower()
                      ~~~~~~~~~^^^^^^^^^
KeyError: 'email'

相关情况说明与解决方案

  • 这类问题确实有不少用户反馈过,核心原因是SendGrid Python SDK的邮箱解析逻辑对含特殊字符(如括号、带注释格式)的邮箱地址处理异常,无法正确解析出email字段,导致后续流程触发KeyError。
  • 常见触发场景包括使用带注释的邮箱格式(例如user(name)@domain.com),SDK的To类在解析这类地址时未正确处理,生成的收件人对象结构不符合预期。
  • 临时修复方案:
    1. 手动构造收件人字典替代To类,绕过SDK的解析逻辑:
      # 替换原To(to_email)的写法
      to_recipient = {"email": to_email}
      message = Mail(from_email=From(config.TEAM_EMAIL, from_name), to_emails=to_recipient)
      
    2. 检查并升级SendGrid Python SDK到最新版本,部分旧版本的解析bug已在后续版本中修复。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 18:22:44