Search code examples
python-3.xdjangohtml-emailpythonanywhere

Django send html email with image as body


I am trying to send an html email with an image in the body using python-Django. But when I try to send the email I get the email without the image. So Tried hard coding a link to an image from the internet into my email context and the email was sent and the picture also did show up but then when i tried to send an email with a picture from my media files it wont load the picture when the user receives it.

I wrote a test function to send an html email but it does not display the picture on the email.

here is my code

def send_html_email(subject, from_email, to_email, html_content):
    # Create the email message
    email = EmailMultiAlternatives(subject, strip_tags(html_content), from_email, to_email)
    email.attach_alternative(html_content, "text/html")

    # Send the email
    email.send()


def send_email_with_picture(request):
    subject = "Example HTML Email"
    from_email = "sender email"
    to_email = ["<recipient email>"]

    # Retrieve the picture URL from your database
    email_instance = Emails.objects.get(subject="Test sending email with picture")
    picture_url = default_storage.url(email_instance.product1_image.name)

    # Retrieve the current domain
    current_site = get_current_site(request)
    domain = current_site.domain

    # Construct the complete absolute URL of the image
    picture_url = f"http://{domain}{picture_url}"

    # Render the HTML content with the absolute image URL
    html_content = render_to_string('email_templates/email_template.html', {'picture_data':picture_url  })

    # Send the email
    send_html_email(subject, from_email, to_email, html_content)

**here is my email template **

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Email Template</title>
</head>
<body>
    <h1>Welcome to our newsletter!</h1>
    <p>Here is a picture for you: {{ picture_data }} ## </p>

    <!-- Render the image directly from the picture_data -->
    <img src="{{ picture_data.url }}" alt="Picture">

    <!-- Additional content for your email -->

</body>
</html>

When I replace
html_content = render_to_string('email_templates/email_template.html', {'picture_data':picture_url }) with a random link to a picture on internet it does send the email with that picture on the body, but fails to do so when i provide a picture from media files

My app is hosted on Pythonanywhere


Solution

  • picture_data is picture_url which gets reset to be a string... f"http://{domain}{picture_url}"

    picture_data, thus, does not have a url property. So picture_data.url is empty.

    You should be able to provide the correct link with simply {{picture_data}} in your template