Outlook接收含指定关键词主题邮件后触发Python脚本
修改后的Outlook VBA代码(按邮件主题关键词触发Python脚本)
我们对原有代码进行了调整,新增了邮件主题关键词校验逻辑,仅当新邮件主题包含你指定的固定词汇时,才会触发Python脚本执行:
Option Explicit 'This "event" runs whenever there is a new email Private Sub Application_NewMailEx(ByVal EntryIDCollection As String) 'Declare as generic Object since we don't know what type of NewMail Item we got yet Dim entry As Object 'Me refers to ThisOutlookSession, the GetNamespace is just something we always have to do in outlook 'GetItemFromID gets the mail object which we need to have to check if its an email 'or if we want to do something with it like move it to another folder Set entry = Me.GetNamespace("MAPI").GetItemFromID(EntryIDCollection) 'Exit our event handler if this isn't an email - meetings and notifications also may pop up here If Not TypeOf entry Is MailItem Then Exit Sub 'Call the sub that will handle the new email 'passing in the email VBA object in case that is important OnNewEmail entry End Sub 'This Sub will be called whenever the Application_NewMailEx event is triggered with a MailItem Private Sub OnNewEmail(ByVal email As MailItem) '定义你需要匹配的固定关键词(按需添加/删除) Dim targetKeywords As Variant targetKeywords = Array("紧急通知", "发票", "告警") '替换为你的目标词汇 Dim keyword As Variant Dim subjectContainsKeyword As Boolean subjectContainsKeyword = False '遍历关键词,检查邮件主题是否包含(不区分大小写) For Each keyword In targetKeywords If InStr(1, email.Subject, keyword, vbTextCompare) > 0 Then subjectContainsKeyword = True Exit For '找到匹配关键词后无需继续检查 End If Next keyword '仅当匹配到关键词时执行Python脚本 If subjectContainsKeyword Then Shell "C:\Program Files\Python310\python.exe C:\Users\lradico\Desktop\WWP\waites_slack.py" End If End Sub
关键说明:
- 请将
targetKeywords数组中的示例词汇替换为你实际需要监测的固定词汇 - 当前校验逻辑为不区分大小写,若需要严格区分大小写,可移除
InStr函数中的vbTextCompare参数 - 修复了原代码中一处未正确注释的代码行,避免运行时错误
内容的提问来源于stack exchange,提问作者L Radico
相关产品推荐
相关产品推荐

