2011-02-22 192 views
31

私はデータを操作できるように、私の交換/ Outlookプロファイル上のフォルダ内の電子メールの内容を読む短いプログラムを書こうとしています。しかし、私はPythonとExchange/Outlookの統合に関する多くの情報を見つけるのに問題があります。物事の多くは非常に古い/ドキュメント/説明されていないいずれかです。私はいくつかのスニペットを試しましたが、同じエラーが発生しているようです。私はエラーを取得するしかしMAPI経由でPythonでOutlookから電子メールを読む

import win32com.client 

session = win32com.client.gencache.EnsureDispatch ("MAPI.Session") 

# 
# Leave blank to be prompted for a session, or use 
# your own profile name if not "Outlook". It is also 
# possible to pull the default profile from the registry. 
# 
session.Logon ("Outlook") 
messages = session.Inbox.Messages 

# 
# Although the inbox_messages collection can be accessed 
# via getitem-style calls (inbox_messages[1] etc.) this 
# is the recommended approach from Microsoft since the 
# Inbox can mutate while you're iterating. 
# 
message = messages.GetFirst() 
while message: 
    print message.Subject 
    message = messages.GetNext() 

:私はティムゴールデンのコードを試してみた

pywintypes.com_error: (-2147221005, 'Invalid class string', None, None) 

なく、私のプロファイル名はので、私はしてみましたが何であるかを確認します。プロンプトが表示されるように

session.Logon() 

をしかし、どちらもうまくいきませんでした(同じエラー)。また、Outlookのオープンとクローズの両方を試してみました。

+1

Outlookクライアントに依存するのではなく、サーバーに対してIMAPを使用することを検討しましたか?あなたのユースケースに応じて、IMAPは実行可能ではるかに移植性が高い(クライアントとサーバーの両方)ことが証明されるかもしれません。 –

+1

@Jason IMAPはうまく見えますが、残念ながら私が使用しているアカウントでは有効になっていません。 – johnharris85

答えて

42

私は同じ問題を抱えていました。しかし、次のコードは、魅力的に機能します。

import win32com.client 

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

inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case, 
            # the inbox. You can change that number to reference 
            # any other folder 
messages = inbox.Items 
message = messages.GetLast() 
body_content = message.body 
print body_content 
+2

他のメッセージ属性を確認する方法はありますか?あなたの例を使って、メッセージが受信された日時を取得したいと思います。 – sequoia

+4

解決策を見つけました:何らかの理由で、何らかの理由でdir()を使用したときに属性が表示されませんでした – sequoia

+5

@sequoia - MicrosoftのMailItemsのCOMプロパティのリスト(例:Outlookメッセージ)を使用すると、メッセージのプロパティ(例:message.SenderEmailAddress):http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.mailitem_properties.aspx – wardw123

8

私は自分のイテレータを作成して、Python経由でOutlookオブジェクトを反復処理しています。問題はPythonがIndex [0]で始まる反復を試みるが、Outlookは最初の項目Index [1]を期待している...もっとRubyをもっと単純にするためには、 のメソッドを持つヘルパークラスOliの下にある:

.items() - タプル(インデックス、項目)を生じる...

.prop() - 利用可能なプロパティ(メソッドと属性)

from win32com.client import constants 
from win32com.client.gencache import EnsureDispatch as Dispatch 

outlook = Dispatch("Outlook.Application") 
mapi = outlook.GetNamespace("MAPI") 

class Oli(): 
    def __init__(self, outlook_object): 
     self._obj = outlook_object 

    def items(self): 
     array_size = self._obj.Count 
     for item_index in xrange(1,array_size+1): 
      yield (item_index, self._obj[item_index]) 

    def prop(self): 
     return sorted(self._obj._prop_map_get_.keys()) 

for inx, folder in Oli(mapi.Folders).items(): 
    # iterate all Outlook folders (top level) 
    print "-"*70 
    print folder.Name 

    for inx,subfolder in Oli(folder.Folders).items(): 
     print "(%i)" % inx, subfolder.Name,"=> ", subfolder 
0

を露出し、Outlookオブジェクトをイントロスペクトするために支援し、私が持っていました同じ問題。インターネット(以上)から様々なアプローチを組み合わせることにより、私も(FileWrapper.pyで見つかった)てFileWriterクラスのコードが含まれconcistencyするために、以下のアプローチ(checkEmails.py)

class CheckMailer: 

     def __init__(self, filename="LOG1.txt", mailbox="Mailbox - Another User Mailbox", folderindex=3): 
      self.f = FileWriter(filename) 
      self.outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI").Folders(mailbox) 
      self.inbox = self.outlook.Folders(folderindex) 


     def check(self):     
     #=============================================================================== 
     # for i in xrange(1,100):       #Uncomment this section if index 3 does not work for you 
     #  try: 
     #   self.inbox = self.outlook.Folders(i)  # "6" refers to the index of inbox for Default User Mailbox 
     #   print "%i %s" % (i,self.inbox)   # "3" refers to the index of inbox for Another user's mailbox 
     #  except: 
     #   print "%i does not work"%i 
     #=============================================================================== 

       self.f.pl(time.strftime("%H:%M:%S")) 
       tot = 0     
       messages = self.inbox.Items 
       message = messages.GetFirst() 
       while message: 
        self.f.pl (message.Subject) 
        message = messages.GetNext() 
        tot += 1 
       self.f.pl("Total Messages found: %i" % tot) 
       self.f.pl("-" * 80) 
       self.f.flush() 

if __name__ == "__main__": 
    mail = CheckMailer() 
    for i in xrange(320): # this is 10.6 hours approximately 
      mail.check() 
      time.sleep(120.00) 

を思い付きます。私はこれが必要でした。なぜなら、WindowsのファイルにUTF8をパイプしようとしている が機能しなかったからです。

class FileWriter(object): 
    ''' 
    convenient file wrapper for writing to files 
    ''' 


    def __init__(self, filename): 
     ''' 
     Constructor 
     ''' 
     self.file = open(filename, "w") 

    def pl(self, a_string): 
     str_uni = a_string.encode('utf-8') 
     self.file.write(str_uni) 
     self.file.write("\n") 

    def flush(self): 
     self.file.flush()  

お楽しみください。

1

私の悪い英語を申し訳ありません。 MAPIでのPythonを使用して チェックのメールの

outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") 
folder = outlook.Folders[5] 
Subfldr = folder.Folders[5] 
messages_REACH = Subfldr.Items 
message = messages_REACH.GetFirst() 

ここでは、メールボックスに、または任意のサブフォルダに最も最初のメールを取得することができ、より簡単です。実際には、メールボックス番号&の向きを確認する必要があります。この分析の助けを借りて、各メールボックス&のサブメールボックスフォルダを確認することができます。

同様に、私たちが見ることができる以下のコード、最後の/以前のメールを見つけてください。どのようにチェックする必要がありますか。

`outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") 
folder = outlook.Folders[5] 
Subfldr = folder.Folders[5] 
messages_REACH = Subfldr.Items 
message = messages_REACH.GetLast()` 

これで、最近のメールをメールボックスに取り込むことができます。 上記のコードによれば、すべてのメールボックス&のサブフォルダを確認できます。

関連する問題