发送电子邮件时出现Outlook pywintypes.com_error

时间:2019-08-30 07:14:20

标签: python python-3.x win32com pythoncom

我第一次使用Outlook发送电子邮件成功。然后,在第二个循环迭代中,它失败了

import threading
import pythoncom  # to lauch mails in threads
import win32com.client as win32  # pip install pywin32, pip install pypiwin32
from datetime import datetime, timedelta
import psutil
import time


def is_outlook_app_open():
    for proc in psutil.process_iter():
        try:
            if(proc.name() == "OUTLOOK.EXE"):
                return True
        except NoSuchProcess:
            pass
    return False


def send_status_email(outlook_id):
    '''
    status email: that the script works
    '''
    recipients = [
        'someone@gmail.com',
    ]

    was_open = is_outlook_app_open()

    # Initialize
    pythoncom.CoInitialize()

    # Get instance from the id
    outlook = win32.Dispatch(pythoncom.CoGetInterfaceAndReleaseStream(
                outlook_id, pythoncom.IID_IDispatch)
    )

    mail = outlook.CreateItem(0)
    for recipient in recipients:
        mail.Recipients.Add(recipient)

    mail.Subject = 'Test Title'
    text_to_send = "Test Text. "
    mail.Body = text_to_send
    mail.Send()

    time.sleep(3)
    if not was_open:
        outlook.Quit()
    print("send_status_email exited. email was sent.")
    return True


class EventManager(threading.Thread):
    def __init__(self):
        '''
        a thread safe outlook initialisation
        '''
        pythoncom.CoInitialize()  # to lauch mails in threads
        # Get instance
        self.outlook = win32.Dispatch('outlook.application')
        # Create id
        self.outlook_id = pythoncom.CoMarshalInterThreadInterfaceInStream(
            pythoncom.IID_IDispatch, self.outlook)
        threading.Thread.__init__(self, kwargs={'outlook_id': 
             self.outlook_id})
        self.event = threading.Event()

    def run(self):
        while not self.event.is_set():
            #BUG: on the second iteration, sending status mail fails
            send_status_email(self.outlook_id)
            time.sleep(120)


if __name__ == "__main__":
    event_manager = EventManager()
    event_manager.start()
    event_manager.join()

我在“ send_status_email”的第二次迭代中收到以下错误: pywintypes.com_error:(-2147417827,“封送处理的接口数据包(OBJREF)格式无效或未知。”,无,无)

0 个答案:

没有答案