LoginSignup
37
58

More than 5 years have passed since last update.

PythonによるOutlookの操作

Last updated at Posted at 2018-07-03

win32comの入手

download

現在の最新版はgithubからのみダウンロード可能
https://github.com/mhammond/pywin32/releases

ただし、このexeを使う方法ではvirtualenvと両立できない。以下を参照して、pipでインストールした。
https://stackoverflow.com/questions/14913607/how-to-install-win32com-module-in-a-virtualenv

(venv) C:\Users\ikedak2\PycharmProjects\Outlook-Analysis>pip install pypiwin32
Collecting pypiwin32

使い方

Inboxを取得する。Indexで取得するらしいが、どのフォルダがどのインデックスなのかを確認する方法は調べても見つけられず。とりあえずはInboxは6で確定らしいので、そこを起点にする。

import win32com.client

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)

そこから先はFoldersというinterfaceを使ってフォルダ名でアクセス可能。

folders = inbox.Folders
devopsFolder = folders('0_標準化関係').folders('0-22_DevOps')

Folderインターフェースはnameというメンバーをもつので(この辺の言葉遣いは正しいか不明)、一覧を出すには、

for folder in folders:
    print('Name: ' + folder.name)

フォルダ内のメッセージにアクセスするには、Itemsというインターフェースを使う。

messages = devopsFolder.Items
for message in messages:
    print('Subject: ' + message.subject)
    print('Sender: ' + message.sendername)
    print('Size: ' + message.subject)
    print('ReceivedTime: ' + str(message.receivedtime))
    print('Body: ' + message.body)

receivedtimeはdatetimeで出力されるので、Stringにして出力している。
アイテムの添付ファイルを保存するには、attachmentsというインターフェースを使う。

for message in messages:
    if message.attachments.count is not 0:
        for attachment in message.attachments:
            print(str(attachment))
            attachment.SaveASFile('C:\\temp\\' + str(attachment))

添付の有り無しは添付の個数が0でないことで判別している。

参考情報

各オブジェクトで指定できるプロパティ等はこちらを参考にする。
https://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.mailitem_properties.aspx

添付ファイルの取得方法
https://hackerpython.wordpress.com/2015/09/29/how-to-download-email-attachments-from-outlook/

37
58
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
37
58