【问题标题】:Copy Word contents into Outlook将 Word 内容复制到 Outlook
【发布时间】:2019-03-18 02:17:21
【问题描述】:

我有一个包含格式化文本、图像和表格的 Word 文档。您可以手动复制其内容并毫无问题地插入 Outlook。如何在 Python 中做到这一点?

我的代码:

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)

最接近的问题:

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

不起作用:

1-将 Word 文档另存为 HTML(类似 RTF)和

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

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

2-读取压缩后的Word文档中的document.xml。

可能的方式:

Inspector 类的 WordEditor 属性返回一个 表示消息正文的 Word 文档。

如何通过win32com应用WordEditor?

【问题讨论】:

  • 我能够复制 RTF 文件的内容,但没有图像。并且桌子被转移了。为此,以'rb' 模式打开文件并设置msg.BodyFormat = 3 # olFormatRichText

标签: python outlook ms-word win32com


【解决方案1】:

在 Alina Li 的帮助下,这是最终的解决方案:

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)

图像、表格、格式 - 一切都很好。

【讨论】:

  • 确保在运行此代码时 Outlook 应用处于打开状态。
【解决方案2】:

您可以使用以下代码将 Word 内容复制到 Outlook 中:

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 () 方法粘贴

【讨论】:

  • 使用什么对象的Paste()方法? msg.Body.Paste() 提高 AttributeError: 'str' object has no attribute 'Paste'
  • 我想通了。这是msg.GetInspector.WordEditor.Range(0).Paste()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多