簡體   English   中英

如何使用Win32com Outlook在Python中刷新電子郵件?

[英]How to refresh an email in Python with win32com Outlook?

我有一個程序可以顯示來自Outlook的最新電子郵件。 如果程序運行時我收到新電子郵件,則不會刷新並顯示新電子郵件。 關於如何執行此操作的任何建議?

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

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()

我發現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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM