Thursday, 3 November 2022

django send email with html template

https://stackoverflow.com/questions/63552113/gmail-schedule-send-email-in-django

https://docs.djangoproject.com/en/4.1/howto/overriding-templates/

https://stackoverflow.com/questions/7537897/django-render-to-string-not-working

https://docs.djangoproject.com/en/4.1/topics/email/

# in settings.py 

# add the following to set up smtp email

EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'your_email'
EMAIL_HOST_PASSWORD = 'your password'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
EMAIL_PORT = 465

# in settings.py change templates variable to change the path of HTML template 
INSTALLED_APPS = [
    ...,
    'blog',
    ...,
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
       
    },


# create your template in name of app
templates/
    blog/
        list.html
        post.html

in list.html
{{context}} to use variable passed from below:

# In your app, do the following :
from smtplib import SMTPException
import sys
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
    html_message = render_to_string('blog/list.html', {'context': 'HELLO WORLD'})
    mail_subject = 'Scheduled Email'
    to_email = 'test@test.com'
    email = EmailMultiAlternatives(mail_subject, plain_message, to=[to_email],)
    email.attach_alternative(html_message, "text/html")
    try:
        email.send(fail_silently=False)
    except SMTPException as smtpe:
        print('SMTPException  -> ', smtpe, file=sys.stderr)

handle exception :

As it says in the Django docs for send_email (https://docs.djangoproject.com/en/1.10/topics/email/#send-mail):

fail_silently: A boolean. If it’s False, send_mail will raise an smtplib.SMTPException. See the smtplib docs for a list of possible exceptions, all of which are subclasses of SMTPException.

So you can do:

from smtplib import SMTPException


No comments:

Post a Comment