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

Python使用Twilio SendGrid发送多附件邮件报can't set attribute错误

错误原因

message.attachments 是SendGrid Python SDK中Mail类的内部只读属性,不支持直接通过等号赋值设置附件列表,直接赋值就会抛出can't set attribute错误。SDK官方提供的附件添加方法是add_attachment(),也就是你代码注释里用到的方法。
原代码另外存在两处可优化/修正的点:

  • 使用with open()上下文管理器读取文件时,会自动完成文件资源释放,不需要手动调用file_data.close()
  • 邮件HTML内容起始标签存在笔误,<stron>为无效标签,正确写法是<strong>
修复方法
  • 移除message.attachments = list(lst_attchments)的直接赋值逻辑
  • 遍历生成好的附件对象列表,逐个调用message.add_attachment()方法添加到邮件实例
  • 清理冗余的文件关闭代码,修正HTML标签笔误
修正后代码
import os
import base64
import logging
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Attachment, FileContent, FileName, FileType, Disposition

message = Mail(
    from_email='from_mail',
    to_emails='to_mail',
    subject='sample mail from fun2 part-no data - 123490-000',
    html_content='<strong>mr. venkatesh, please find the updated data and let me know if any issues. \n regards,System</strong>'
)

try:
    sg = SendGridAPIClient(os.environ.get('sendgridkey'))
    # 如需自动读取临时目录下所有文件,可替换为下一行代码,无需硬编码文件名
    # files = [f for f in os.listdir(temp_path) if os.path.isfile(os.path.join(temp_path, f))]
    files = ["test_file.pdf", "test_file2.pdf", "test_file1.pdf"]

    for file_name in files:
        file_path = os.path.join(temp_path, file_name)
        with open(file_path, 'rb') as file_data:
            data = file_data.read()
        encoded_file = base64.b64encode(data).decode()

        attachedFile = Attachment(
            FileContent(encoded_file),
            FileName(file_name),
            # 非pdf文件可根据文件后缀匹配对应MIME类型,实现多类型文件附件支持
            FileType('application/pdf'),
            Disposition('attachment')
        )
        # 逐个添加附件,替代直接赋值attachments属性的写法
        message.add_attachment(attachedFile)
    
    mail_json = message.get()        
    response = sg.client.mail.send.post(request_body=mail_json)
    logging.info('mail sent succefully')
    
except Exception as e:
    logging.error(e)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 02:33:27