Django Template Email

0

DJANGO: Could anyone help me put email template (pull some html or css to email content) through views.py? I tried everything but it did not work, grateful already.

Views.py:

- - coding: utf-8 - -

from django.shortcuts import render from django.conf import settings

from django.core.mail import send_mail

from .forms import contactForm # importing forms.py class

Create your views here.

def contact (request):     title = 'Contact'     form = contactForm (request.POST or None)     confirm_message = None

if form.is_valid():
    comment = form.cleaned_data['comment']
    name = form.cleaned_data['name']
    subject = 'Mensagem vinda de MEUSITE.com'
    message = ' %s %s' %(comment, name)
    emailFrom = form.cleaned_data['email']
    emailTo = [settings.EMAIL_HOST_USER]
    send_mail(subject, message, emailFrom, emailTo, fail_silently=True)
    title = "Nós agradecemos!!"
    confirm_message = "Obrigado pela mensagem!"
    form = None

context = { 'title': title, 'form': form, 'confirm_message': confirm_message}
template = 'contact.html'
return render(request, template, context)

Forms.py:

- - coding: utf-8 - -

from django import forms

class contactForm (forms.Form):     name = forms.CharField (label = 'Name:', required = False, max_length = 100, help_text = 'max 100 characters')     email = forms.EmailField (label = 'Email:', required = True)     comment = forms.CharField (label = 'Comment:', required = True, widget = forms.Textarea)

    
asked by anonymous 14.02.2016 / 22:55

1 answer

1

Oops, I hope this helps:

from django.template.loader import get_template
from django.utils.safestring import mark_safe
from django.template import Context
from django.core.mail import EmailMessage

...

content = get_template('template_email.html').render(Context({'meu_objeto': meu_objeto}))

email = EmailMessage('titulo', mark_safe(content) ,'[email protected]', to=['[email protected]'])
email.content_subtype = 'html'
email.send()

In your html, just call your css files for the entire domain.

<link rel="stylesheet" href="http://localhost:8000/static/css/meucss.css">

When playing for production, you should call by the application domain:

<link rel="stylesheet" href="http://www.meusite.com.br/static/css/meucss.css">

Or send http_host through the context and call it:

content = get_template('template_email.html').render(Context({'host': request.META['HTTP_HOST']}))

And in the template:

<link rel="stylesheet" href="http://{{host}}/static/css/meucss.css">

I hope it helps.

    
15.02.2016 / 13:38