Sending a html email in Django [duplicate]

2020-06-09 05:38发布

Since Django 1.7 has come out things have changed a bit. Im trying to use 'send_mail' to send a HTML email.

I want to send a thank you email to users after signing up to my site.

Im using

subject = 'Thank you from ******'
message = 'text version of HTML message'
from_email = my email address
to_list = users email address
html_message= really long set of html code

send_mail(subject,message,from_email,to_list,fail_silently=True,html_message=html_message) 

Is it possible to store the html as a file on the server and then convert it into a string so that it can be fed into 'html_message'?

1条回答
够拽才男人
2楼-- · 2020-06-09 06:12

Yes, you can. In my own project, I use the following code to do the same thing:

from django.template import loader

html_message = loader.render_to_string(
            'path/to/your/htm_file.html',
            {
                'user_name': user.name,
                'subject':  'Thank you from' + dynymic_data,
                //...  
            }
        )
send_mail(subject,message,from_email,to_list,fail_silently=True,html_message=html_message)

And the html file looks like this:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <h1>{{ user_name }}</h1>
        <h2>{{ subject }}</h2>
    </body>
</html>
查看更多
登录 后发表回答