I am not able to add an image in email body using

2019-04-14 11:42发布

问题:

Right now I am using below code:

import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'to address'
mail.Subject = 'Message subject'
mail.Body = 'Message body'
mail.HTMLBody = '<h2>HTML Message body</h2>'# this field is optional
**mail.Attachments.Add('C:\Users\MA299445\Downloads\screenshot.png')**
mail.Send()

I am able to attach a picture but I want to paste this picture in e-mail body.

Thanks in advance

回答1:

Create an attachment and set the PR_ATTACH_CONTENT_ID property (DASL name "http://schemas.microsoft.com/mapi/proptag/0x3712001F") using Attachment.PropertyAccessor.

Your HTML body (MailItem.HTMLBody property) would then need to reference that image attachment through the cid:

img src="cid:xyz"

where xyz is the value of the PR_ATTACH_CONTENT_ID property.

Look at an existing message with OutlookSpy (click IMessage button).

attachment = mail.Attachments.Add("C:\Users\MA299445\Downloads\screenshot.png")
attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "MyId1")
mail.HTMLBody = "<html><body>Test image <img src=""cid:MyId1""></body></html>"


回答2:

You can use <img> HTML tag:

encoded_image = base64.b64encode(image_file.getvalue()).decode("utf-8")
html = '<img src="data:image/png;base64,%s"/>' % encoded_image

And you can put the tag inside your HTML content.

Don't forget to import required modules:

import base64