[Django]-Inserting a Django URL into a custom email template

3👍

Not sure about your template, but if I remember Django urls correctly, you can use reverse in your code and pass the resolved url to your template through context. So it’d be something like this:

from django.core.mail import EmailMessage
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
from django.urls import reverse

subject, from_email = 'subject', '<info@mysite.com>'
plaintext = get_template('email.txt')
htmly = get_template('email.html')
username = user.username
d = { 'username': username, 'url': reverse('home') }
text_content = plaintext.render(d)
html_content = htmly.render(d)            
msg = EmailMultiAlternatives(subject, text_content, from_email, [user.email])
msg.attach_alternative(html_content, "text/html")
msg.send()

Template:

<h3>Hi <strong>{{ username }}</strong>,</h6>
<p> disown kvdsvnsdov vknvisodvnsdv dsdov siod vsd. Here is a link:</p>
<a href="http://domain{{ url }}">Check Now</a>
👤kaveh

0👍

I think that you are missing the absolute URL in the link within your email template.

When you send out an email, Django fills in the URL with a relative URL and perhaps your Gmail mail client is filling in URL with its own domain and language prefix path.

You need to add the domain name of your current site from within a Django template.

The <a> will look like this:

<a href="{{ request.scheme }}://{{ request.get_host }}{% url 'home' %}">Check Now</a>

To render a template for an email, which is one of the cases where you’d want the host value:

from django.template.loader import render_to_string

def view(request):
    ...
    email_body = render_to_string(
        'template.txt', context, request=request)

Leave a comment