我想移动所有收到的电子邮件,这些邮件不是来自我公司的域名(例如JohnDeer@tractorworld.com),并且在主题字段中没有我公司的名称到垃圾邮件文件夹。
这是我到目前为止所做的,但它在几百次迭代后给了我一个类型不匹配的错误:
Sub SpamHunter()
Dim inBox As Folder
Set inBox = Session.GetDefaultFolder(olFolderInbox)
MsgBox ("Items Found: " & inBox.Items.count)
Dim mailItem As mailItem
Dim b As Long
Dim mailAddress As String
Dim mailSubject As String
Dim mailReceived As Date
Dim c As Integer
c = 0
For Each mailItem In inBox.Items
c = c + 1
mailAddress = mailItem.SenderEmailAddress
mailSubject = mailItem.Subject
mailReceived = mailItem.ReceivedTime
b = InStr(mailAddress, "mycompany")
b = b + InStr(mailAddress, "myothercompany")
If b < 1 Then
mailItem.Move (Session.GetDefaultFolder(olFolderInbox).Folders("_Junk"))
End If
Next
End Sub
答案 0 :(得分:1)
并非收件箱中的所有内容都是MailItem
。例如,会议请求不是MailItem
。
在将项目投射到该类型之前,您需要检查该项目是否为mailitem。
Dim o as Object
Dim ixItems as Integer
For ixItems = inBox.Items.Count To 1 Step -1
Set o = inBox.Items.Item(ixItems)
if TypeName(o) = "MailItem" Then
Set mailItem = o
' loop goes here
c = c + 1
mailAddress = mailItem.SenderEmailAddress
mailSubject = mailItem.Subject
mailReceived = mailItem.ReceivedTime
b = InStr(mailAddress, "mycompany")
b = b + InStr(mailAddress, "myothercompany")
If b < 1 Then
mailItem.Move (Session.GetDefaultFolder(olFolderInbox).Folders("_Junk"))
End If
End If
Next
另外,提示:不要让变量名称与类型名称冲突。我建议您调用变量oMailItem
或类似变量,因此很明显它是一个变量而非类型。