django send_notification UnicodeEncodeError:'ascii'编解码器无法编码字符

时间:2014-02-11 05:08:01

标签: python django heroku notifications

我无法用类似问题提供的信息来解决这个问题,所以这里有。基本上我有一个简单的命令,可以根据某些条件向我的用户发送电子邮件。它遍历列表或收件人,并向符合条件的任何人发送电子邮件。它通过一些电子邮件在本地工作正常,但是当我将我的一面推向heroku并遍历我的用户列表时,我收到以下错误。我不认为这是一个heroku问题,但我没有一个很好的方法来解决问题:

UnicodeEncodeError: 'ascii' codec can't encode character

这是我的简单命令:

import logging
logger = logging.getLogger(__name__)
from datetime import datetime, timedelta, time
from django.core.management.base import BaseCommand, CommandError
from django.core.mail import send_mass_mail, EmailMultiAlternatives
from django.conf import settings
from django.utils import timezone
from notifications.mail import send_notification
from users.models import User

class Command(BaseCommand):
    def handle(self, *args, **options):
        now = timezone.now()
        day = str(settings.WEEKLY_EMAIL_STATUS_DAY)
        email_go = str(settings.WEEKLY_EMAIL_STATUS)
        last_login_time = timezone.now() - timedelta(days=7)

        if email_go == ("True"):
            if now.strftime("%A").encode('utf-8') == day:
                recipients = list(User.objects.filter(weekly_updates=True, last_login__lte=last_login_time ))
                send_notification(recipients, "notifications/weekly_account_update.txt")

以下是使用的mail.py:

import logging
logger = logging.getLogger(__name__)
import re
import mimetypes

from django.conf import settings
from django.core.mail import send_mass_mail, EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
from email.mime.text import MIMEText


def send_notification(recipient, template, **variables):

    """Also accepts list of `recipient`s which will send a mail to each."""
    if isinstance(recipient, list):
        recipients = recipient
    else:
        recipients = [recipient]

    variables['root_url'] = settings.PUBLIC_URL_ROOT
    messages = []
    for recipient in recipients:
        variables['recipient'] = recipient
        message = get_template(template).render(Context(variables))
        subject, html_content = re.split(r'\n+', message.strip(), maxsplit=1)

        for message in messages:
            message = EmailMultiAlternatives(html_content)
            message = MIMEText(html_content, 'html')
            message.content_subtype = "html"

        messages.append((
            subject,
            html_content,
            settings.NOTIFACTION_FROM_ADDRESS,
            [recipient.email]))



    send_mass_mail(messages, fail_silently=False)
    logger.info("Sent %r email to %s" % (template, ', '.join(r.email for r in recipients)))

weekly_account_update.txt:

{% load cents %}
{% autoescape on %}You've got {{recipient.account.balance|credits}} unspent credits.{%   endautoescape %}

Hey {% autoescape on %}{{recipient.first_name}}{{recipient.last_name}}{% endautoescape %},

You've got {{recipient.account.balance|credits}} unspent credits left to use. Here's some great stuff you could be reading and supporting: {{root_url}}{% url 'home' %}#trending


-Team

0 个答案:

没有答案