在 Outlook 中使用来自 VBA 的参数启动 Python 脚本

Launching Python script with arguments from VBA in Outlook

我试图在将电子邮件移动到特定文件夹时触发 Python 脚本。

我们的想法是在 Outlook 中设置一个规则,当电子邮件包含特定关键字时将其移动到特定文件夹,然后让 VBA 脚本启动带有参数的 Python 脚本新项目被添加到文件夹中。我正在关注 this guide.

Option Explicit
Private objNS As Outlook.NameSpace
Private WithEvents objItems As Outlook.Items

Private Sub Application_Startup()
    Dim objWatchFolder As Outlook.Folder
    Set objNS = Application.GetNamespace("MAPI")

    Set objWatchFolder = objNS.GetDefaultFolder(olFolderInbox)
    Set objItems = objWatchFolder.Items

    Set objWatchFolder = Nothing
End Sub


Private Sub objItems_ItemAdd(ByVal Item As Object)
    MsgBox "Message subject: " & Item.Subject & vbcrlf & "Message sender: " & Item.SenderName &" (" & Item.SenderEmailAddress & ")"
    Dim subject As Item.subject
    Shell("""C:\Path\to\python.exe"" ""C:\Path\With Spaces\script.py """ & subject)
    Set Item = Nothing
End Sub

以前,在使用 Dim subject As Item.subject 声明主题变量后,以下工作正常:

Shell("""C:\path\to\python.exe"" ""C:\Path\With Spaces\To\Script\Hello.py """ & subject)

现在出现编译错误

user-defined type not defined.

此错误发生在 Dim subject As Item.subject 行。

当我尝试通过以下方式将电子邮件的主题传递给 Python 脚本时:

Shell("""C:\path\to\python.exe"" ""C:\Path\With Spaces\To\Script\Hello.py """ & Item.subject)

它没有崩溃,但看起来 Python 脚本从未运行过。

当我这样做时:

Shell("""C:\path\to\python.exe"" ""C:\Path\With Spaces\To\Script\Hello.py "" & Item.subject")

它将 &Item.subject 作为字符串参数传递 - 未传递存储在 Item.subject 中的电子邮件主题,但文字字符串“Item.subject”。

为什么 Dim subject As Item.subject 现在会导致错误以及如何将电子邮件的主题作为参数传递给我的 Python 脚本?

我认为您的问题是调用 python 代码时双引号分配和间距不正确。我还假设主题中可以有空格,所以应该用双引号引起来(假设我有正确的调用命名法):

"""C:\Path\to\python.exe"" ""C:\Path\With Spaces\script.py"" """ & Item.subject & """"

在调用 运行 和 python 脚本之前,您可以使用 Debug.Print 检查字符串是否符合预期。免责声明:我没有使用 python 脚本,因此未经测试

Option Explicit
Private WithEvents objItems As Outlook.Items

Private Sub Application_Startup()
    With Application.Outlook
        Set ObjItems = .GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Items
    End With
End Sub

Private Sub objItems_ItemAdd(ByVal Item As Object)
    If TypeName(Item) = "MailItem" Then
        Dim strFunc As String: strFunc = """C:\Path\to\python.exe"" ""C:\Path\With Spaces\script.py"" """ & Item.subject & """"
        Debug.Print strFunc
        Shell strFunc, vbMinimizedNoFocus
    End If
End Sub