Django Template Email

Asked

Viewed 240 times

0

DJANGO: Could someone help me place an email template (pull some html or css to the email content) through the views.py? I tried everything that way but it didn’t work, thanks from now on.

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)

1 answer

2

Whoa, 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 by the full domain.

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

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

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

Or send http_host in 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.