发送HTML电子邮件Django 1.9

时间:2017-09-05 14:52:52

标签: python django

我试图创建一个使用send_mass_email发送HTML电子邮件回复的联系表单,但我一直收到语法错误。

我在views.py中有以下代码

def email(request, template='marketing/email.html'):
    form = ContactForm(request.POST or None)
    if form.is_valid():
        subject = form.cleaned_data['subject']
        from_email = form.cleaned_data['from_email']
        message = form.cleaned_data['message']
        html_content = render_to_string(
            'marketing/welcome.html',
            {
                'message': message,
                'subject': subject,

            }
        )
        try:
            message1 = (subject, message, from_email, ['test@test.com'], html_message=html_content)
            message2 = (subject, message, from_email, ['test@test.com'], html_message=html_content)
            send_mass_mail((message1, message2), fail_silently=False)
        except BadHeaderError:
            return HttpResponse('Invalid header found.')
        return redirect('thanks')
    context = {
            "form": form,

        }
    return render(request, template, context)

def thanks(request):
    return HttpResponse('Thank you for your message.')

我一直收到以下错误。

    message1 = (subject, message, from_email, ['test@test.com'], html_message=html_content)
SyntaxError: invalid syntax

2 个答案:

答案 0 :(得分:1)

发送电子邮件的良好做法是附加HTML和纯文本版本:

msg = EmailMultiAlternatives(subject, message_plaintext, from_email, recipient_list)
msg.attach_alternative(message_html, "text/html")

然后,给定一堆EmailMultiAlternatives个实例,您可以通过connection.send_messages(messages)批量发送所有这些实例 - 请参阅this answer

答案 1 :(得分:1)

这是最终的工作版本。

# Mass Send Email function  

def get_rendered_html(template_name, context={}):
    html_content = render_to_string(template_name, context)
    return html_content


def send_email(subject, html_content, text_content=None, from_email=None, recipients=[], attachments=[], bcc=[], cc=[]):
    # send email to user with attachment
    if not from_email:
        from_email = settings.DEFAULT_FROM_EMAIL
    if not text_content:
        text_content = ''
    email = EmailMultiAlternatives(
        subject, text_content, from_email, recipients, bcc=bcc, cc=cc
    )
    email.attach_alternative(html_content, "text/html")
    for attachment in attachments:
        # Example: email.attach('design.png', img_data, 'image/png')
        email.attach(*attachment)
    email.send()


def send_mass_mail(data_list):
    for data in data_list:
        template = data.pop('template')
        context = data.pop('context')
        html_content = get_rendered_html(template, context)
        data.update({'html_content': html_content})
        send_email(**data)


# Contact Form 
def HomePage(request, template='marketing/home.html'):
    form = ContactForm(request.POST or None)
    if form.is_valid():
        name = form.cleaned_data['name']
        from_email = form.cleaned_data['from_email']
        message = form.cleaned_data['message']
        phone = form.cleaned_data['phone']
        # Create message1 to send to poster
        message1 = {
        'subject': 'Test',
        'text_content': message,
        'from_email': from_email,
        'recipients': [from_email],
        'template': "marketing/welcome.html",
        'context': {"message": message,
                    "name": name,
                    "phone": phone,

                    }


        }
        # Create message1 to send to website admin
        message2 = {
        'subject': 'Test',
        'text_content': message,
        'from_email': from_email,
        'recipients': ['test@test.com'],
        'template': "marketing/welcome.html",
        'context': {"message": message,
                    "name": name,
                    "phone": phone,

                    }


        }

        try:
            send_mass_mail([message1])

        except BadHeaderError:
            return HttpResponse('Invalid header found.')
        return redirect('thanks')
    context = {
            "form": form,

        }
    return render(request, template, context)

def thanks(request):
    return HttpResponse('Thank you for your message.')