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

Azure Databricks发送邮件报错NoCredentialsError:无法定位凭证

解决Azure Databricks发送邮件时的NoCredentialsError问题

核心原因

你参考的文档是AWS环境下使用SES发送邮件的方案,代码默认会自动读取AWS访问凭证(比如环境变量、本地凭证文件),但Azure Databricks环境中没有配置这些AWS凭证,因此触发NoCredentialsError。

可行解决方案

方案1:改用Azure原生邮件服务(推荐)

使用Azure Communication Services(ACS)发送邮件,适配Azure生态,无需依赖AWS凭证:

  1. 安装依赖包
    %pip install azure-communication-email
    
  2. 在Azure门户创建ACS资源,获取连接字符串,将其存入Databricks Secret Scope(避免硬编码)
  3. 发送邮件示例代码:
    from azure.communication.email import EmailClient
    
    # 从Databricks Secrets读取ACS连接字符串,替换为你的Secret Scope和Key
    connection_string = dbutils.secrets.get(scope="your-secret-scope", key="acs-connection-string")
    email_client = EmailClient.from_connection_string(connection_string)
    
    email_message = {
        "senderAddress": "verified-sender@your-domain.com",  # 需在ACS中验证发件人
        "recipients": {"to": [{"address": "recipient@example.com"}]},
        "content": {
            "subject": "Azure Databricks测试邮件",
            "html": "<h3>这是通过ACS发送的测试邮件</h3>"
        }
    }
    
    # 发送并获取结果
    poller = email_client.begin_send(email_message)
    send_result = poller.result()
    print(f"邮件发送成功,消息ID:{send_result.message_id}")
    

方案2:继续使用AWS SES发送邮件

如果必须用SES,需在Azure Databricks中显式配置AWS凭证:

  1. 在AWS IAM创建具备ses:SendEmail权限的用户,获取Access Key ID和Secret Access Key
  2. 将这两个凭证存入Databricks Secret Scope
  3. 修改代码,显式传入凭证初始化SES客户端:
    import boto3
    from botocore.exceptions import ClientError
    
    # 从Secrets读取AWS凭证
    aws_access_key = dbutils.secrets.get(scope="your-secret-scope", key="aws-access-key-id")
    aws_secret_key = dbutils.secrets.get(scope="your-secret-scope", key="aws-secret-access-key")
    
    # 显式初始化SES客户端
    ses_client = boto3.client(
        "ses",
        region_name="us-east-1",  # 替换为你的SES服务区域
        aws_access_key_id=aws_access_key,
        aws_secret_access_key=aws_secret_key
    )
    
    # 发送邮件
    try:
        response = ses_client.send_email(
            Source="verified-sender@your-domain.com",  # SES中已验证的发件人
            Destination={"ToAddresses": ["recipient@example.com"]},
            Message={
                "Subject": {"Data": "AWS SES测试邮件"},
                "Body": {"Html": {"Data": "<h3>通过AWS SES发送的测试邮件</h3>"}}
            }
        )
    except ClientError as e:
        print(f"发送失败:{e.response['Error']['Message']}")
    else:
        print(f"邮件发送成功,消息ID:{response['MessageId']}")
    
    注意:需确保SES已验证发件人邮箱/域名,且IAM用户权限配置正确。

关键注意事项

  • 禁止硬编码任何凭证,必须通过Databricks Secret Manager存储和读取
  • 使用方案2时,需确保Databricks集群网络能访问AWS SES服务端点

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:55:21