2016-07-07 111 views
0

我已經閱讀thisthisthis但沒有有效的答案。 我試圖使用Django發送郵件與html_message,似乎唯一的出路是:Django send_mail:AttributeError:'list'對象沒有屬性'encode'

send_mail(
    subject=_(u"My news"), 
    message=message, html_message=html_message, 
    from_email=u'[email protected]', 
    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'[email protected]', 
      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) 
+0

請打印:'type(personne.user.email)'並顯示它的類型。 – Gocht

+0

'' –

+1

我剛剛嘗試了相同的代碼,並且它工作正常,請在您的設置中添加您的配置以發送電子郵件 – Gocht

回答

0

你上一次更新後,我可以在你的函數send_newsletter看到這一行:

... 
html_message = [m, u"\n"] 
... 

然後你使用附加功能添加內容html_message。因此,您可以創建一個列表,即使沒有指定這個docs不,應該是用HTML格式的字符串:

html_message = "<strong>Hi there!</strong>" 

嘗試在send_mail函數傳遞一個字符串中的屬性html_message

+0

你是對的,榮譽! –

相關問題