Django send_mail:AttributeError:' list'对象没有属性' encode'

时间:2016-07-07 15:04:17

标签: django encoding character-encoding

我已经阅读了thisthisthis但没有有效答案。 我试图用html_message与Django一起发送邮件,似乎唯一可行的方法是:

send_mail(
    subject=_(u"My news"),
    message=message, html_message=html_message,
    from_email=u'contact@cogofly.com',
    recipient_list=[personne.user.email, ])

(虽然没有BCCEmailMessage()函数有一个......)。 当我尝试这些线时,我得到:

in send_newsletter, recipient_list=[personne.user.email, ]
AttributeError: 'list' object has no attribute 'encode'

我做错了什么?

这是我的settings.py配置:

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

并且没有其他任何关于邮件发送(我在开发机器上)

我试图按照文档here

进行操作

这里是整个错误堆栈跟踪:

Traceback (most recent call last):
  File "C:\Program Files (x86)\JetBrains\PyCharm 2016.1\helpers\pycharm\django_manage.py", line 41, in <module>
    run_module(manage_file, None, '__main__', True)
  File "C:\Python27\lib\runpy.py", line 176, in run_module
    fname, loader, pkg_name)
  File "C:\Python27\lib\runpy.py", line 82, in _run_module_code
    mod_name, mod_fname, mod_loader, pkg_name)
  File "C:\Python27\lib\runpy.py", line 72, in _run_code
    exec code in run_globals
  File "C:\Users\Olivier\PycharmProjects\cogofly\manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 354, in execute_from_command_line
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 346, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 394, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 445, in execute
    output = self.handle(*args, **options)
  File "C:/Users/Olivier/PycharmProjects/cogofly\app\management\commands\sendnewsletter.py", line 124, in handle
    self.send_newsletter(p)
  File "C:/Users/Olivier/PycharmProjects/cogofly\app\management\commands\sendnewsletter.py", line 92, in send_newsletter
    recipient_list=[personne.user.email, ])
  File "C:\Python27\lib\site-packages\django\core\mail\__init__.py", line 62, in send_mail
    return mail.send()
  File "C:\Python27\lib\site-packages\django\core\mail\message.py", line 303, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "C:\Python27\lib\site-packages\django\core\mail\backends\console.py", line 36, in send_messages
    self.write_message(message)
  File "C:\Python27\lib\site-packages\django\core\mail\backends\console.py", line 18, in write_message
    msg = message.message()
  File "C:\Python27\lib\site-packages\django\core\mail\message.py", line 266, in message
    msg = SafeMIMEText(self.body, self.content_subtype, encoding)
  File "C:\Python27\lib\site-packages\django\core\mail\message.py", line 184, in __init__
    self.set_payload(_text, utf8_charset)
  File "C:\Python27\lib\email\message.py", line 226, in set_payload
    self.set_charset(charset)
  File "C:\Python27\lib\email\message.py", line 268, in set_charset
    cte(self)
  File "C:\Python27\lib\email\encoders.py", line 73, in encode_7or8bit
    orig.encode('ascii')
AttributeError: 'list' object has no attribute 'encode'

这是我的代码:

class Command(ActivitesMixin, MessagesNotReadMixin, InvitationsMixin,
              LikesMixin, BaseCommand):
    help = 'Send the newsletter to members'
    can_import_settings = True

    def __init__(self, *args, **kwargs):
        super(Command, self).__init__(*args, **kwargs)
        self.requires_system_checks = True  # test bd bien synchro, entre autres
        self.output_transaction = True  # dump visuel de SQL

    def add_arguments(self, parser):
        parser.add_argument('--reset_all_news',
                            action='store_true',
                            dest='reset_all_news',
                            default=None,
                            help='Reset ALL news and resend ALL to EVERYBODY')
        parser.add_argument('--reset_personne_id',
                            action='store_true',
                            dest='reset_personne_id',
                            default=None,
                            help='Reset newsletter of a specific person')

    def send_newsletter(self, personne):
        if personne.site_language is None:
            return
        if personne.site_web is None:
            return
        print personne.site_language, personne.site_web

        translation.activate(personne.site_language.locale)
        f = get_format('DATE_INPUT_FORMATS')[1]
        m = _(u"Here is the latest news on your contacts, "
              u"along with other notifications that might be of "
              u"interest to you, since your last connection:")
        message = [m, u"\n"]
        html_message = [m, u"\n"]
        # prendre toutes les activites dans la langue de la personne :
        news_sent = PersonneActiviteNewsletter.objects.filter(personne=personne)
        a = self.activites(personne, personne.site_language).exclude(
            pk__in=news_sent.values_list('activite__pk'))

        for activite in a:
            message.append(_(u"- {}, {}:\n{}\n").format(
                activite.date_last_modif.strftime(f),
                activite.date_last_modif.strftime('%H:%M'),
                activite.description(with_date=False)))
            html_message.append(_(u"- {}, {}:\n{}\n").format(
                activite.date_last_modif.strftime(f),
                activite.date_last_modif.strftime('%H:%M'),
                activite.description(with_date=False, tag='b')))

        n = self.messages_not_read(personne).count()
        if n > 0:
            m = ungettext(u'You have {} message not read.\n',
                          u'You have {} messages not read.\n', n).format(n)
            message.append(m)
            html_message.append(m)
        n = self.messages_not_read(personne).count()
        if n > 0:
            m = ungettext(u'You have {} invitation not read.\n',
                          u'You have {} invitations not read.\n', n).format(n)
            message.append(m)
            html_message.append(m)
        n = self.likes(personne).count()
        if n > 0:
            m = ungettext(u'You have {} like!\n',
                          u'You have {} likes!\n', n).format(n)
            message.append(m)
            html_message.append(m)

        print personne.user.email
        print type(personne.user.email)
        print settings.EMAIL_BACKEND
        send_mail(
            subject=_(u"Cogofly's news"),
            message=message, html_message=html_message,
            from_email=u'contact@cogofly.com',
            recipient_list=[personne.user.email, ])

        translation.deactivate()

    def handle(self, *args, **options):
        if options['reset_all_news']:
            try:
                reset = bool(options['reset_all_news'])
            except ValueError:
                raise CommandError('reset_all_news has to be a boolean')

        if options['reset_personne_id']:
            try:
                personne_id = int(options['reset_all_news'])
            except ValueError:
                raise CommandError('reset_personne_id has to be an integer')

            try:
                p = Personne.objects.get(pk=personne_id)
            except Personne.DoesNotExist:
                raise CommandError('Personne {} not found'.format(personne_id))

            self.send_newsletter(personne=p)
        else:
            tab = Personne.objects.filter(est_detruit__isnull=True)
            for p in tab.filter(date_v_fin__isnull=True,
                                est_active__exact=True):
                self.send_newsletter(p)

1 个答案:

答案 0 :(得分:0)

在您上次更新后,我可以在您的函数... html_message = [m, u"\n"] ... 中看到此行:

html_message

然后使用追加功能将内容添加到html_message = "<strong>Hi there!</strong>" 。因此,您创建了一个列表,即使docs未指定此列表,也应该是HTML格式的字符串:

html_message

尝试在send_mail函数中的属性.class中传递字符串。