创建键盘快捷键以使用 pynput 和 pywin32 发送电子邮件

问题描述 投票:0回答:1

我正在尝试设置键盘快捷键以使用 pywin32 从 Outlook 发送电子邮件。我收到此错误,我猜这是因为 pynput 和 win32com 都在访问 Windows API?但我对 Windows 编程和 Python 很陌生,所以任何帮助将不胜感激。

    outlook = win32.Dispatch('outlook.application')
  File "C:\Users\lukew\AppData\Local\Programs\Python\Python38-32\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch
    dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
  File "C:\Users\lukew\AppData\Local\Programs\Python\Python38-32\lib\site-packages\win32com\client\dynamic.py", line 114, in _GetGoodDispatchAndUserName
    return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "C:\Users\lukew\AppData\Local\Programs\Python\Python38-32\lib\site-packages\win32com\client\dynamic.py", line 91, in _GetGoodDispatch
    IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None)
    import win32com.client as win32
    from pynput import keyboard
    
    class Action:
    
        def send_mail(self):
            outlook = win32.Dispatch('outlook.application')
            mail = outlook.CreateItem(0)
            mail.To = 'Luke Wood'
            mail.Subject = 'Mail subject'
            mail.Body = 'Hello'
    
            mail.Send()
    
    class Hot:
    
        def __init__(self, action):
            self.action = action
            self.listener = keyboard.Listener(win32_event_filter=self.win32_event_filter)
            with self.listener as ml:
                ml.join()
    
        def down(self, key):
            if key == 162:
                self.action.send_mail()
    
        def win32_event_filter(self, msg, data):
            if msg == 256:
                self.down(data.vkCode)
            return True
    
    action = Action()
    Hot(action)
    
    input()

Windows 10 x64 - Python 3.8.2 - Outlook 2019

python windows pywin32 win32com pynput
1个回答
0
投票

您可以使用

win32
来发送 Outlook 电子邮件,而不是使用
redmail
。请注意,您必须先安装
redmail
才能使用它。这是一个简短的例子:

from pynput.keyboard import Listener
from redmail import outlook

def on_press(key):
    if key.char == 's':
        outlook.user_name = '[email protected]'
        outlook.password = 'mysecretpassword1234'

        outlook.send(
            receivers=['[email protected]'],
            subject='test',
            text='This is a test'
        )

with Listener(on_press=on_press) as listener:
    listener.join()
© www.soinside.com 2019 - 2024. All rights reserved.