2012-07-16 37 views
3

我有以下功能(Django的)發出邀請:Gmail中不顯示嵌入式圖像的

def send_invitation(self, request): 
    t = loader.get_template('email/invitation.html') 
    html_content = t.render(Context(context)) 
    message = EmailMessage('Hi there', html_content, '[email protected]', 
      [self.profile_email], 
      headers={'Reply-To': 'Online <[email protected]>'}) 
    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不會立即顯示圖像。

當我檢查電子郵件的來源它確實增加了正確的頭:

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中的電子郵件時?

PS。我查看了關於內嵌圖像的所有主題,但仍然無法在Gmail中工作

回答

1

僅因安全原因,Gmail不支持自動圖像加載。旨在限制電子郵件中包含的圖像數量,因爲它們通常會導致spam-trapped

電子郵件客戶端通常會允許圖像顯示(尤其是如果它們是用base-64之類的東西編碼的話)。 Gmail的瀏覽器端電子郵件根本就不是這種情況。如果您非常關心顯示圖像,則可以使用base64編碼將其嵌入。這將顯着增加電子郵件的文件大小(您將其包括在內,而不是通過引用),所以請謹慎使用(或者您將被垃圾郵件捕獲器過濾)。

參考http://docs.python.org/library/base64.html

享受和好運氣!