Cannot get the image position in the body from Outlook Python API

Viewed 17

I need some help, I am currently trying to do some scripting to automatize some tasks. I would like to fetch the received mail and send the body somewhere.

For that I am using win32.com with the outlook API.

But the issue is that if there is image in the body of the mail. I can't fetch it with the initial body. I Thought about using attachment, which is working but in the end, I have images and the body. But in the body I don't have the image position information... So I can only send the images and cannot set them correctly. Which can be difficult to understand if there is a lot of images...

So far the code looks like something like this :

import os
import win32com.client

outlook = win32com.client.Dispatch('outlook.application')

mapi = outlook.GetNamespace("MAPI")
inbox = mapi.GetDefaultFolder(6)

messages = inbox.Items
message = messages[len(messages) - 1]

body = message.body

attachments = message.attachments
attachment = attachments[0]

file_name = attachment.filename

path = "D:\\Documents\\tmp"
attachment.SaveAsFile(path + os.sep + attachment.FileName)

Do you have any help on this ? Thanks for your help :)

PS : Do you know where I can find the Python documentation for outlook API, I just find the Rest API one and there is some difference from both. Or if we can get the source code to check directly.

1 Answers

In the message body you may check for <img/> tags. If any of them contains this tag with a file name prefixed with cid: string, for example:

<img src=cid:Filename/>

Then you deal with an embedded image which can be found in attached files.

Also you may check the PR_ATTACH_CONTENT_ID property on the attached files in the following way:

Const PR_ATTACH_CONTENT_ID = "http://schemas.microsoft.com/mapi/proptag/0x3712001F"

Function IsEmbedded(Att As Attachment) As Boolean
    Dim PropAccessor As PropertyAccessor
    Set PropAccessor = Att.PropertyAccessor
    IsEmbedded = (PropAccessor.GetProperty(PR_ATTACH_CONTENT_ID) <> "")
End Function

The PropertyAccessor can help you to deal with low-level MAPI properties in Outlook.

Related