2017-04-04 134 views
0

我有一個程序,顯示我最近從Outlook電子郵件。如果我在程序運行時收到新電子郵件,它不會刷新並顯示新電子郵件。有關我如何做到這一點的任何建議?如何使用win32com Outlook在Python中刷新電子郵件?

我的代碼沒有更新到最新的電子郵件:

import win32com.client 
import os 
import threading # use the Timer 

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 

def timer(): 


    print (body_content) 

    threading.Timer(30, timer).start() 

timer() 

回答

0

我發現了COM庫未在新線程初始化。因此,我不得不把它添加到功能

import pythoncom   # These 2 lines are here because COM library 
    pythoncom.CoInitialize() # is not initialized in the new thread 

這將是正確的代碼工作:

def timer(): 

    import pythoncom   # These 2 lines are here because COM library 
    pythoncom.CoInitialize() # is not initialized in the new thread 

    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 

    os.system('cls' if os.name == 'nt' else 'clear') 
    print (body_content) # orginally used body_content.encode("utf-8") to fixed character encoding issue 
         # caused by Windows CMD. But then figured out you can type 'chcp 65001' in cmd 
    threading.Timer(30, timer).start() # refresh rate goes her 
相關問題