Kanchon Gharami
Kanchon Gharami

Reputation: 949

Django sending emails with links is not working

I am trying to send a mail with an attached link in Django.

my views.py:

def mail_report(request, pk):
    admin_objs = Admin.objects.order_by()
    Report_obj = Report.objects.filter(pk=pk).first()

    to = []
    for i in admin_objs:
        to.append(i.email)

    mail_report_dict = {
        'report' : Report_obj,
    }
    html_content = render_to_string("app/mail_report.html", mail_report_dict)
    text_content = strip_tags(html_content)

    email = EmailMultiAlternatives(
        "Industry Inspection Report from Project Surokkha",
        text_content,
        settings.EMAIL_HOST_USER,
        to
    )
    email.send()

    return redirect('app:index')

my template:

<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <h3>Hello Admin,</h3>
    <p>
      Inspection Report of {{ report.name }} 
    </p>
    <p>
      Please check the report:
      <a href="https://html2canvas.hertzen.com/configuration" style="color: skyblue;">
        report link
      </a>
    </p>

  </body>
</html>

But when The mail received, there is no hyperlink present with the word report link. N.B.: I check the mail_report.html in my browser also, that contains the link perfectly.

How can I fix this?

Upvotes: 0

Views: 501

Answers (2)

Randall Arms
Randall Arms

Reputation: 516

Attach html_content to the email object like this:

email.attach_alternative(html_content, "text/html")

Upvotes: 1

yvesonline
yvesonline

Reputation: 4847

You forgot to attach the alternative html_content, i.e. change your use of EmailMultiAlternatives to:

email = EmailMultiAlternatives(
    "Industry Inspection Report from Project Surokkha",
    text_content,
    settings.EMAIL_HOST_USER,
    to
)
email.attach_alternative(html_content, "text/html")
email.send()

See also the Django documentation.

Upvotes: 3

Related Questions