如何在 Django 中将图像作为电子邮件正文的一部分发送

问题描述

我正在构建一个用于发送动态电子邮件的门户。表单的一部分是一个图像字段,用户可以上传我希望在图像正文中呈现的图像,而不是在填写表单后作为附件。这是我的代码

views.py

def emailView(request):
    if request.method == 'POST':
        
        form = ContactForm(request.POST,request.FILES)

        if form.is_valid():
            form.save()
            name = form.cleaned_data['name']
            subject = form.cleaned_data['subject']
            image = form.cleaned_data['image']
            message = form.cleaned_data['message']
            recipient = form.cleaned_data['recipient']

            image_url = Email.objects.all().last()
            domain = request.get_host()

            final_image = str(domain) + str(image_url.image.url)

            msg = loader.render_to_string(
                'email_portal/email.html',{
                    'name': name,'subject': subject,'domain' : domain,'final_image' : final_image,'image_url': image_url,'message': message,}
            )

            try:
                 send_mail(subject,name,message,[recipient],fail_silently=True,html_message=msg,)
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('/')
    else:

        form = ContactForm(request.POST,request.FILES)

    return render(request,"email_portal/index.html",{'form': form})

电子邮件.html

<h5>{{ final_image }}</h5> #missing forward slash
<a href="{{ domain }}/{{ image_url.image.url }}">My link</a> #missing forward slash
<tr>
<td background="{{ final_image }}</td>
</tr>

我尝试将主机和文件路径连接起来,但由于某种原因,在电子邮件正文中,它的结构是正确的,但我无法将其呈现为背景图像,并且当我尝试单击它时,中间缺少正斜杠主机和文件路径。

解决方法

假设 {{ final_image }}{{ domain }}/{{ image_url.image.url }} 相同并且除了网址之外不添加任何其他内容,我会尝试这样做:

<td style="background-image: url('{{ final_image }}');">

这是对你正在做的事情的一个小调整,但它有效。但是,这在 Outlook 2007-2019 中不起作用。

对于适用于包括 Outlook 在内的大多数电子邮件客户端的解决方案,我会尝试这样做:

<td valign="middle" style="text-align: center; background-image: url('{{ final_image }}'); 
background-position: center center !important; background-size: cover !important;">
  <!--[if gte mso 9]>
  <v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" 
  style="width:600px;height:400px; background-position: center center !important;">
  <v:fill type="tile" src="{{ final_image }}" />
  </v:rect>
  <![endif]-->
</td>

Outlook 的一个问题是,如果您没有设置宽度和高度并且图像大于电子邮件的宽度,Outlook 将显示图像的全宽。忽略 max-widthwidth 等 CSS 样式。因此,除非您有一些代码将图像大小处理为最大宽度,否则这是一个考虑因素。

background-size: cover !important; 将确保现代电子邮件客户端将空白填充到您指定为最大宽度的大小。