首页 > 解决方案 > 如何使用 MultiEmailAlternatives 嵌入带有 html 的图像?

问题描述

在这里,我尝试将图像与 html 模板一起发送。为此,我遵循两种方法 1> 第一种方法我制作了 logo_data() 函数来获取图像,然后我附加了这个方法msg.attach(logo_data())msg.attach_alternative()但这种方法没有用。2>在第二种方法中,我通过上下文与方法将 current_site 发送到模板,get_current_site()并在模板中使用静态标签定义图像,但我也没有解决。

我如何也可以发送带有图像的电子邮件。发送 html 模板工作正常,只有模板上的图像没有显示

<img src="{{site}}{% static 'dist/img/logo.png' %}"

视图.py

def logo_data():
    with open(finders.find('static/dist/img/logo.png'), 'rb') as f:
        logo_data = f.read()
    logo = MIMEImage(logo_data)
    logo.add_header('Content-ID', '<logo>')
    return logo

def send_mail(request):
.............
            site=get_current_site(request)
            html_content = render_to_string('mailverification/guest_notification_after_cleaning.html',{'site':site.domain})
            subject, from_email, to = 'Hello', settings.EMAIL_HOST_USER, email
            msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
            msg.attach_alternative(html_content, "text/html")
            msg.attach(logo_data())
            msg.send() 
            return HttpResponse('mail send')

标签: django

解决方案


推荐阅读