使用 Django 在 HTML 电子邮件模板中将图像作为内联附件发送

Sending Images as inline Attachment within HTML Email template using Django

我正在尝试发送一封 HTML 会呈现内联图像的电子邮件。我在views.py中的代码如下:

import ...

def signup_mail_function(form):      # here, form is just my context 
    subject = "Signup Successful"
    html_message = render_to_string('emailTemplate.html', {'form': form})
    plain_message = strip_tags(html_message)
    from_email = 'uconnect786@gmail.com'
    to_email = [form.email]

    # Sending email here
    msg = EmailMultiAlternatives(subject=subject, body=plain_message, from_email=from_email,to=to_email)                               
    msg.attach_alternative(html_message, "text/html")
    msg.content_subtype = 'html'
    msg.mixed_subtype = 'related'

    img_path = settings.STATIC_DIR + '/images/blogsImage.svg'  # path of my image
    image_name = Path(img_path).name      # Testing image name,which returns out to be same as image    name i.e blogsImage.svg
    print(img_path, image_name)                              # testing image paths here
    with open(img_path, 'rb') as f:
        image = MIMEImage(f.read(), _subtype="svg+xml")
        msg.attach(image)
        image.add_header('Content-ID', "<{}>".format(image_name))    # Setting content ID
        print("<{}>".format(image_name))                       # Testing content ID

    msg.send()

以上是我的邮件消息处理代码。在模板中,我正在执行以下操作:

<img  alt="Blog Image"  src="cid:blogsImage.svg" />

电子邮件以图片作为附件成功发送,但实际上我希望在 Html 页面中将图片作为内嵌图片获取。

我收到的电子邮件,您看到 Html 模板中没有显示任何图像,因此会弹出这些图像的 'alt' 标签

我可以对整个 Html 页面进行快照,但在其下方,我将该图像作为附件。

尝试过:

我还尝试使用如下直接 URL 在我的 Html 模板中测试图像插入:

<img src="https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=.........." alt="Image">

但这也没有成功。我几乎阅读了每篇关于使用 Django 渲染内联图像的文章和博客、堆栈溢出问题和答案,但其中 none 对我有用,尽管我的编码方式相同。 请有人在这里为我指明正确的方向!

首先你应该在view.py

中导入以下代码

从 email.mime.image 导入 MIMEImage 导入 os

def signup_mail_function(form):
msg = EmailMultiAlternatives(subject=subject, body=plain_message, 
from_email=from_email,to=to_email)
msg.content_subtype = 'html'
msg.mixed_subtype = 'related'
img_path = os.path.join(settings.BASE_DIR, '/images/blogsImage.svg')
with open(banner_path, 'rb') as banner_image:
    banner_image = MIMEImage(img_path.read())
    banner_image.add_header('Content-ID', '<blogsImage.svg>')
    msg.attach(banner_image)
msg.send()

并在 html 模板中

<img  alt="Blog Image"  src="cid:blogsImage.svg" />

我找到了问题的答案...! 问题并不像我预期的那样出在代码中,而是在图像中,我试图在我的电子邮件中发送一个 'SVG' 图像,许多电子邮件客户端甚至 Gmail 都不支持,所以这就是问题所在。该代码适用于其他格式。 您可以在此处获得有关支持的电子邮件格式的更多信息: