【问题标题】:Adding width and height to local image in new mail in outlook with win32com(Python)使用win32com(Python)在Outlook中的新邮件中为本地图像添加宽度和高度
【发布时间】:2021-11-08 21:49:11
【问题描述】:

为什么我不能将宽度和高度传递给 img 标签中的本地图像。下面的代码正在工作(正在显示图像)但是当我将width="100" height="200" 添加到 img 标签时,图像不显示。当我将 src 更改为网络上的图像 src="https://i.stack.imgur.com/GafDJ.jpg?s=256&g=1" 并添加 width="100" height="200" 时,图像会显示添加的尺寸。


import os
import win32com.client as client
outlook = client.Dispatch('Outlook.Application')

mail = outlook.CreateItem(0)
icon = os.getcwd() + '\\test.jpg'

html_body = f'''
<img src="{icon}">
<!-- <img src="https://i.stack.imgur.com/GafDJ.jpg?s=256&g=1" width="100" height="200"> -->

'''

mail.To = ''
mail.CC = ''
mail.Subject = ''
mail.HTMLBody = html_body
mail.Save()

【问题讨论】:

    标签: python windows outlook win32com


    【解决方案1】:

    本地图片需要作为附件添加,否则实际图片不会随电子邮件一起发送。过去对我有用的过程是将图像文件添加为附件,然后将其作为邮件中 html 的属性引用。

    例如:

    import os
    import win32com.client as client
    
    outlook = client.gencache.EnsureDispatch('Outlook.Application')
    
    mail = outlook.CreateItem(client.constants.olMailItem)
    icon = os.getcwd() + '\\Test.jpg'
    
    #Add a new attachment, putting 0 as third argument means the file is hidden
    att = mail.Attachments.Add(icon,client.constants.olByValue,0)
    
    #Create a Content Id (cid) for this image. Can be whatever you want: I'm using short filename
    cidName = icon.split('\\')[-1]
    att.PropertyAccessor.SetProperty('http://schemas.microsoft.com/mapi/proptag/0x3712001F', cidName);
        
    imgTag = '<img src="cid:{0:}" width="100" height="200">'.format(cidName)
    
    mail.To = ''
    mail.CC = ''
    mail.Subject = ''
    mail.HTMLBody = imgTag
    mail.Save()
    

    我不是关于整个“模式”如何工作的专家,但它似乎可以完成这项工作。注意。我使用了gencache.EnsureDispatch() 而不仅仅是Dispatch()。我发现这可以确保 Outlook 常量可用(例如 olByValue),而不仅仅是使用硬编码的数字。

    【讨论】:

    • 不指定宽高时可以发送带图片的邮件。
    • @IGRACH 我明白你的意思了!我现在记得必须走附件路线,因为我的图像没有正确显示。有很多关于 Outlook 未“正确”呈现 HTML 的链接,例如:blog.jmwhite.co.uk/2014/03/28/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 2018-09-01
    • 1970-01-01
    • 2013-06-17
    相关资源
    最近更新 更多