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

测试Django信号发送邮件时遇‘list’对象无splitlines属性错误求助

解决Django信号发送邮件时的‘list' object has no attribute 'splitlines’错误

嘿,这个问题的根源很容易找到——你犯了两个关键错误:参数类型不对和参数顺序搞反了!

错误原因拆解

  1. 不该把参数包装成列表
    你把firstname、subject、email都用[]包装成了列表(比如firstname = [instance.firstname]),但Django的send_mail函数需要的是字符串类型的参数。列表没有splitlines方法(这个方法是字符串用来拆分换行的),这就是触发报错的直接原因。

  2. send_mail的参数顺序完全错了
    Django的send_mail正确参数顺序是:

    send_mail(subject, message, from_email, recipient_list, fail_silently=False, ...)
    

    你现在传的是send_mail(firstname, subject, email, ['cmadiam@abc.com']),相当于把名字当成了主题,主题当成了邮件内容,完全不符合函数要求。

修正后的代码示例

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.mail import send_mail
from .models import Booking  # 确保导入你的Booking模型

@receiver(post_save, sender=Booking)
def new_booking(sender, instance, **kwargs):
    # 先确保instance有firstname和有效的邮箱
    if instance.firstname and instance.email:
        # 直接取字符串,不要包装成列表
        firstname = instance.firstname
        from_email = instance.email
        service = instance.service
        
        # 定义清晰的邮件主题和内容(都是字符串)
        subject = f"新预订确认:{service}"
        message = f"您好{firstname}!\n\n感谢您预订{service}服务,我们会尽快与您联系。\n\n祝好!"
        
        # 按正确顺序调用send_mail
        send_mail(
            subject=subject,
            message=message,
            from_email=from_email,
            recipient_list=['cmadiam@abc.com'],
            fail_silently=False
        )

额外提醒

  • 确保instance.email是格式合法的邮箱字符串,否则邮件发送会失败
  • 如果需要在邮件里添加更多信息(比如预订日期、时间),直接把这些字段转换成字符串拼到message里就行
  • fail_silently=False会在邮件发送失败时抛出异常,方便你调试,上线生产环境前可以考虑改成True或者添加异常捕获逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:12:00