I've already read this, this and this but no valid answer.
I'm trying to send mail with Django with html_message
and it seems the only way to go is:
send_mail(
subject=_(u"My news"),
message=message, html_message=html_message,
from_email=u'contact@cogofly.com',
recipient_list=[personne.user.email, ])
(though there's no BCC
whereas EmailMessage()
function has one...).
When I try those lines I get:
in send_newsletter, recipient_list=[personne.user.email, ]
AttributeError: 'list' object has no attribute 'encode'
What am I doing wrong?
Here's my settings.py
configuration:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
and nothing else about mail sending (i'm on a development machine)
and I'm trying to follow the documentation here:
Here's the whole error stack trace:
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'
Here's my code:
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)