1

I have a Word document with formatted text, images, and tables. You can manually copy its contents and insert into Outlook with no problems. How to do it in Python?

My code:

import win32com.client

word = win32com.client.Dispatch("Word.Application")
doc = word.Documents.Open(your_doc_path)
contents = 'What here?'  # doc.Content?

outlook = win32com.client.Dispatch("Outlook.Application")
# Create a new MailItem object
msg = outlook.CreateItem(0)

msg.Body = 'What here?'  # `contents` throws pywintypes.com_error
msg.Display(False)

The closest problems:

Copy Word format into Outlook message

A word document's contents as the body of an email message

How to paste into Outlook from Microsoft Word

Exporting rich text to outlook and keep formatting

Does not work:

1-Saving a Word doc as HTML (analogously RTF) and

with open(html_path, 'r', errors='ignore') as f:
    # Possible UnicodeDecodeError
    doc_body = f.read()

    msg.BodyFormat = 2  # olFormatHTML
    msg.Body = doc_body

2-Reading document.xml in the zipped Word document.

Possible way:

The WordEditor property of the Inspector class returns an instance of the Word Document which represents the message body.

How to apply WordEditor via win32com?

Max
  • 1,685
  • 16
  • 21
  • I was able to copy contents of a RTF file, but without images. and the tables are shifted. For that, open the file in `'rb'` mode and set `msg.BodyFormat = 3 # olFormatRichText` – Max Oct 12 '18 at 22:17

2 Answers2

1

With the help of Alina Li, here is the final solution:

import win32com.client

word = win32com.client.Dispatch("Word.Application")
doc = word.Documents.Open(word_path)
doc.Content.Copy()
doc.Close()

outlook = win32com.client.Dispatch("Outlook.Application")
# Create a new MailItem object
msg = outlook.CreateItem(0)
msg.GetInspector.WordEditor.Range(Start=0, End=0).Paste()

msg.Display(False)

Images, tables, format - everything is good.

Max
  • 1,685
  • 16
  • 21
-1

You could copy Word contents into Outlook with the below code:

import win32com.client
app=win32com.client.Dispatch('Word.Application')
doc=app.Documents.Open(r'D:\winGUI\test\1.doc')
doc.Content.Copy()
doc.Close()

Paste using the Paste () method

Alina Li
  • 884
  • 1
  • 6
  • 5
  • Using `Paste()` method of what object? `msg.Body.Paste()` raises `AttributeError: 'str' object has no attribute 'Paste'` – Max Oct 15 '18 at 18:35
  • I figured out. It's `msg.GetInspector.WordEditor.Range(0).Paste()`. – Max Oct 15 '18 at 19:06