python - Gmail 不显示内联图片

标签 python django email gmail mime

我有以下功能 (Django) 来发出邀请:

def send_invitation(self, request): 
    t = loader.get_template('email/invitation.html')
    html_content = t.render(Context(context))
    message = EmailMessage('Hi there', html_content, 'to@some.com',
            [self.profile_email],
            headers={'Reply-To': 'Online <online@online.nl>'})
    message.content_subtype = 'html'
    localize_html_email_images(message)
    message.send()

我正在使用一个函数将本地提供的链接图像替换为附加图像。

def localize_html_email_images(message):
    import re, os.path
    from django.conf import settings

    image_pattern = """<IMG\s*.*src=['"](?P<img_src>%s[^'"]*)['"].*\/>""" % settings.STATIC_URL

    image_matches = re.findall(image_pattern, message.body)
    added_images = {}

    for image_match in image_matches:
        if image_match not in added_images:
            img_content_cid = id_generator()
            on_disk_path = os.path.join(settings.STATIC_ROOT, image_match.replace(settings.STATIC_URL, ''))
            img_data = open(on_disk_path, 'r').read()
            img = MIMEImage(img_data)
            img.add_header('Content-ID', '<%s>' % img_content_cid)
            img.add_header('Content-Disposition', 'inline')
            message.attach(img)

            added_images[image_match] = img_content_cid

    def repl(matchobj):
        x = matchobj.group('img_src')
        y = 'cid:%s' % str(added_images[matchobj.group('img_src')])

        return matchobj.group(0).replace(x, y)

    if added_images:
        message.body = re.sub(image_pattern, repl, message.body)

一切正常。但不知何故,Gmail 不会立即显示图像,而 Hotmail 和 Outlook 会。

当我检查电子邮件的来源时,它确实添加了正确的 header :

Content-Type: multipart/mixed; boundary="===============1839307569=="
#stuff
<IMG style="DISPLAY: block" border=0 alt="" src="cid:A023ZF" width=600 height=20 />
#stuff
Content-Type: image/jpeg
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-ID: <A023ZF>
Content-Disposition: inline

如何使 Gmail 像 Hotmail 和 Outlook 一样在打开电子邮件时立即显示图像?

附言。我查看了很多关于内嵌图片的主题,但它在 Gmail 中仍然不起作用

最佳答案

出于安全原因,Gmail 将不支持自动加载图片。旨在限制电子邮件中包含的图像数量,因为它们通常会导致被垃圾邮件诱捕

电子邮件客户端通常会允许显示图像(特别是如果图像以 base-64 之类的方式编码)。对于 Gmail 等浏览器端电子邮件来说,情况就完全不同了。如果您非常关心图像的显示,您可以使用 base64 编码嵌入它。这将显着增加电子邮件的文件大小(您按值而不是按引用包括它)因此请谨慎使用(否则您将被垃圾邮件捕获器过滤)。

引用:http://docs.python.org/library/base64.html

祝你好运!

关于python - Gmail 不显示内联图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11507574/

相关文章:

python - 夹层中的每个帖子有多个作者

python - 除了这些方法之外,如何获取路径的子文件夹名称?

python: pycodestyle (ex pep8) vs pylint 严格性

python - django应用程序多个硬盘驱动器[Errno 18]无效的跨设备链接

python - 如何在单个 Django 模型中存储任意类型的值?

python - 如何检查数据框(Pandas)中是否存在所有可能的列组合?

django - 具有基于类的 View 的多个表单。如何在同一页面显示错误?

php - Laravel 邮件附件超时

php - PHP 变量电子邮件地址中带撇号的字符串值,mysql select

python - 如何使用 SMTP 发送附件?