Django发送带图片的HTML邮件

9

我正在尝试使用Django 1.3发送带有图像的HTML电子邮件,但我的图片无法加载。以下是我的view.py文件:

email_data = {
# Summary data
'user_name':user_name,
'points':user.numOfPoints,
}
email_data = RequestContext(request, email_data)
t = get_template('user_email.html')
content = t.render(email_data)
msg = EmailMessage(subject='User Email', content, 'admin@company.com', ['user@gmail.com'])
msg.content_subtype = "html"
msg.send()

我的模板('user_email.html')如下所示

<html>
<body>
Hello {{user_name}},
Your point score is: {{points}}
Thank you for using our app.
<img src="{{ STATIC_URL }}images/footer.jpg" alt="" />
<body>
</html>

这张图片位于我的应用文件夹的static/image文件夹中。但是当我收到邮件时,邮件中没有图片。

在我的settings.py文件中,我有以下内容:

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.contrib.messages.context_processors.messages',
)
STATIC_URL = '/static/'

请告诉我我缺少什么?

谢谢。


邮件中图像的渲染URL是什么? - iMom0
渲染图像的URL为http://static/images/footer.jpg。 - Muhammad Abbas
2个回答

7

正如roam提到的那样,您缺少主机名+端口。

对于那些使用Django的allauth包进行身份验证的用户(https://www.djangopackages.com/packages/p/django-allauth/),您可以简单地使用{{site}},例如:

<img src="{{site}}{{ STATIC_URL }}images/footer.jpg" alt="" />

更好的方法是,使用%static注释:
{% load static %}
...
<img src="{{site}}{% static 'images/footer.jpg' %}" alt="" />

4
您需要指定完整的STATIC_URL,例如http://localhost:8000/static/。当前消息指向/static/images/footer.jpg,这不是一个有效的URL。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接