I want when Outlook opens to:
Search sent items with today's date with a specific subject.
If none is found, then send the "Test" email.
If found, display messagebox that says "Email is found".
I have only been able to do #1.
Private Sub Application_Startup()
Dim MItem As MailItem
Set MItem = Application.CreateItem(olMailItem)
MItem.Subject = "Test Alert"
MItem.To = "email#abc.com"
MItem.DeferredDeliveryTime = DateAdd("n", 1, Now) 'n = minute, h=hour
MItem.Send
End Sub
Update:
This is what I've tried. It doesn't seem to be searching the Sent Items folder with the subject.
Public Function is_email_sent()
Dim olApp As Outlook.Application
Dim olNs As Outlook.NameSpace
Dim olFldr As Outlook.Folder
Dim olItms As Outlook.Items
Dim objItem As Outlook.MailItem
On Error Resume Next
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set olFldr = olNs.GetDefaultFolder(Outlook.olFolderSentMail)
For Each objItem In olFldr.Items
If objItem.Subject = "Test Alert" And _
objItem.SentOn = Date Then _
MsgBox "Yes. Email found"
Else
MsgBox "No. Email not found"
Exit For
End If
Next objItem
End Function
The main error is misuse of On Error Resume Next. Errors are bypassed, not fixed.
Public Sub is_email_sentFIX()
Dim olFldr As Folder
Dim olItms As Items
Dim objItem As Object
Dim bFound As Boolean
' Not useful here.
' Use for specific purpose to bypass **expected** errors.
'On Error Resume Next
Set olFldr = Session.GetDefaultFolder(olFolderSentMail)
Set olItms = olFldr.Items
olItms.sort "[SentOn]", True
For Each objItem In olItms
If objItem.Class = OlMail Then
Debug.Print objItem.Subject
If objItem.Subject = "Test Alert" Then
Debug.Print objItem.SentOn
Debug.Print Date
If objItem.SentOn > Date Then
MsgBox "Yes. Email found"
bFound = True
Exit For
End If
End If
End If
Next objItem
If bFound = False Then
MsgBox "No. Email not found"
End If
End Sub
If there are an excessive number of items in the Sent folder the "not found" outcome will be slow.
One possible option to the brute force way is to Restrict to the specific item, rather than using If statements.
this is some code ive used;
Sub sendmail10101() 'this is to send the email from contents in a cell
Dim obApp As Object
Dim NewMail As MailItem
Set obApp = Outlook.Application
Set NewMail = obApp.CreateItem(olMailItem)
'You can change the concrete info as per your needs
With NewMail
.Subject = Cells(21, 3).Value
.To = Cells(18, 3).Value
.Body = "Good day" & vbCrLf & "i hope you are keeping well " & vbCrLf & vbCrLf & "please can you assist with the below members infomation;" & vbCrLf & vbCrLf & vbCrLf & Cells(20, 3).Value
'.Attachments.Add ("C:\Attachments\Test File.docx")
.Importance = olImportanceHigh
.Display
End With
Set obApp = Nothing
Set NewMail = Nothing
End Sub
the next part is to search the mail box, which you can also use to search from the first initial cell;
Option Explicit
Public Sub Search_Outlook_Emails()
Dim outApp As Outlook.Application
Dim outNs As Outlook.Namespace
Dim outStartFolder As Outlook.MAPIFolder
Dim foundEmail As Outlook.MailItem
Set outApp = New Outlook.Application
Set outNs = outApp.GetNamespace("MAPI")
'Start at Inbox's parent folder
Set outStartFolder = outNs.GetDefaultFolder(Outlook.olFolderInbox).Parent
'Or start at folder selected by user
'Set outStartFolder = outNs.PickFolder
If Not outStartFolder Is Nothing Then
Set foundEmail = Find_Email_In_Folder(outStartFolder, ThisWorkbook.Sheets("Dashboard").TextBox1.Value)
If Not foundEmail Is Nothing Then
If MsgBox("Email subject: " & foundEmail.Subject & vbNewLine & vbNewLine & _
"Folder: " & foundEmail.Parent.FolderPath & vbNewLine & vbNewLine & _
"Open the email?", vbYesNo, "'" & ThisWorkbook.Sheets("Dashboard").TextBox1.Value & "' found") = vbYes Then
foundEmail.Display
End If
Else
MsgBox "", vbOKOnly, "'" & ThisWorkbook.Sheets("Dashboard").TextBox1.Value & "' not found"
End If
End If
End Sub
Private Function Find_Email_In_Folder(outFolder As Outlook.MAPIFolder, findText As String) As Outlook.MailItem
Dim outItem As Object
Dim outMail As Outlook.MailItem
Dim outSubFolder As Outlook.MAPIFolder
Dim i As Long
Debug.Print outFolder.FolderPath
Set Find_Email_In_Folder = Nothing
'Search emails in this folder
i = 1
While i <= outFolder.Items.Count And Find_Email_In_Folder Is Nothing
Set outItem = outFolder.Items(i)
If outItem.Class = Outlook.OlObjectClass.olMail Then
'Does the findText occur in this email's body text?
Set outMail = outItem
If InStr(1, outMail.Body, findText, vbTextCompare) > 0 Then Set Find_Email_In_Folder = outMail
End If
i = i + 1
Wend
DoEvents
'If not found, search emails in subfolders
i = 1
While i <= outFolder.Folders.Count And Find_Email_In_Folder Is Nothing
Set outSubFolder = outFolder.Folders(i)
'Only check mail item folders
If outSubFolder.DefaultItemType = Outlook.olMailItem Then Set Find_Email_In_Folder = Find_Email_In_Folder(outSubFolder, findText)
i = i + 1
Wend
End Function
the previous code brings us a message box to say if its been found which can be removed but maybe use the message box and an IF statement
such as;
with activeworkbook
if msgbox.value = "yes" then
range("A1:A30") = "COMPLETED" 'ASSUMING THIS IS THE INTIAL TEST RANGE IT WILL CHANGE THE SUBJECT THUS STOPPING THE FIRST MACRO
end if
end with
or if no message box then use something such as IF found then so on...
hope this helps
Related
I have this code that creates an email, fills in the to, cc, subject fields; and I want it to text the table that I manually copied from the Internet. So basically I want it to do a ctrl-v in the body of the email. I have tried the doclipboard.GetText method and a few other methods. This is the most recent try.
Sub SendEmail(ByVal strSubject As String, ByVal strBody As String, ByVal blnDisplay As Boolean, ByVal blnAddPaste As Boolean)
Dim bStarted As Boolean
Dim oOutlookApp As Outlook.Application
Dim oItem As Outlook.MailItem
On Error Resume Next
'Get Outlook if it's running
Set oOutlookApp = GetObject(, "Outlook.Application")
If Err <> 0 Then
'Outlook wasn't running, start it from code
Set oOutlookApp = CreateObject("Outlook.Application")
bStarted = True
End If
'Create a new mailitem
Set oItem = oOutlookApp.CreateItem(olMailItem)
With oItem
'Set the recipient for the new email
.To = "Email Addresses"
'Set the recipient for a copy
'.CC = strCC
'Set the subject
.Subject = "Salesforce " & EmailDateFormat & " " & strSubject
'The content of the document is used as the body for the email
If blnAddPaste Then
.HTMLBody = strBody & "<br><br>" & _
Selection.PasteAndFormat(Word.WdRecoveryType.wdTableOriginalFormatting) ' this is what I need to fix
Else
.HTMLBody = strBody
End If
If blnDisplay Then
.Display
Else
.Send
End If
End With
If bStarted Then
'If we started Outlook from code, then close it
oOutlookApp.Quit
End If
'Clean up
Set oItem = Nothing
Set oOutlookApp = Nothing
End Sub
How do I get a table to paste inside of the outlook email?
I figured it out for anyone else looking for the solution.
Sub SendEmail(ByVal strSubject As String, ByVal strBody As String, ByVal blnDisplay As Boolean, ByVal blnAddPaste As Boolean)
Dim bStarted As Boolean
Dim oOutlookApp As Outlook.Application
Dim oItem As Outlook.MailItem
Dim oWordDoc As Word.Document
Dim oWordRange As Word.Range
Dim VarPosition As Variant
On Error Resume Next
'Get Outlook if it's running
Set oOutlookApp = GetObject(, "Outlook.Application")
If Err <> 0 Then
'Outlook wasn't running, start it from code
Set oOutlookApp = CreateObject("Outlook.Application")
bStarted = True
End If
'Create a new mailitem
Set oItem = oOutlookApp.CreateItem(olMailItem)
With oItem
If blnDisplay Then
.Display
End If
Set oWordDoc = oItem.GetInspector.WordEditor
'Set the recipient for the new email
.To = "Email Addresses"
'Set the recipient for a copy
'.CC = strCC
'Set the subject
.Subject = "Salesforce " & EmailDateFormat & " " & strSubject
'The content of the document is used as the body for the email
If blnAddPaste Then
.Body = strBody '& Selection.PasteAndFormat(Word.WdRecoveryType.wdTableOriginalFormatting)
VarPosition = oWordDoc.Range.End - 1
Set oWordRange = oWordDoc.Range(VarPosition, VarPosition)
oWordRange.Select
oWordRange.PasteAndFormat (Word.WdRecoveryType.wdFormatOriginalFormatting)
'SendKeys ("^v")
Else
.HTMLBody = strBody
End If
If Not blnDisplay Then
.Send
End If
End With
If bStarted Then
'If we started Outlook from code, then close it
oOutlookApp.Quit
End If
'Clean up
Set oItem = Nothing
Set oOutlookApp = Nothing
End Sub
I'm trying to set up a form so that when a subject - in the example I have, it's animals - is selected from a ComboBox, it changes both the file name and also the subject line of the email. Currently, it just sends an email when you click the submit button, but I need to differentiate between files depending on which subject is selected. I've tried searching for an answer, but I've so far not come across anything related.
The ComboBox has four entries in it. Tiger, Monkey, Elephant, Giraffe.
The ComboBox is named "Animals" and it's tag is "ComboBox1"
Unfortunately, for whatever reason, I am unable to upload a picture, but it is a "Combo Box Content Control" if that helps. Apologies, I have limited knowledge of this stuff, it's mostly been trial and error to get me to this point and borrowing other pieces of code.
Any suggestions would be helpful.
Private Sub Submit_Click()
Dim objOutlook As Object
Dim objOutlookMsg As Object
Dim objInspector As Object
Dim objDoc As Word.Document
Dim objRange As Range
Dim sDocname As String
ActiveDocument.Save
sDocname = ActiveDocument.FullName
If Len(ActiveDocument.Path) = 0 Then
MsgBox "Document is not saved!"
GoTo lbl_Exit
End If
On Error Resume Next
Set objOutlook = GetObject(, "Outlook.Application")
If Err <> 0 Then
MsgBox "Outlook is not running."
GoTo lbl_Exit
End If
On Error GoTo 0
Set objOutlookMsg = objOutlook.createitem(0)
With objOutlookMsg
.To = "email#emailaddress.com"
.Cc = ""
.Subject = "Favourite Animal is "
.attachments.Add sDocname
Set objInspector = .GetInspector
Set objDoc = objInspector.WordEditor
Set objRange = objDoc.Range(0, 0)
.Display
objRange.Text = "My favourite animal is the "
.Send
End With
lbl_Exit:
Set objDoc = Nothing
Set objRange = Nothing
Set objOutlookMsg = Nothing
Set objInspector = Nothing
Set objOutlook = Nothing
Exit Sub
End Sub
What about something like this?
Private Sub Submit_Click()
Dim objOutlook As Object
Dim objOutlookMsg As Object
Dim objInspector As Object
Dim objDoc As Word.Document
Dim objRange As Range
Dim sDocname As String
'new declarations.
Dim cmb As ContentControl
Dim sSelText As String
'get a reference of the combobox.
Set cmb = ThisDocument.SelectContentControlsByTag("Combobox1")(1)
'get the selected item in a variable.
sSelText = cmb.Range.Text
Set cmb = Nothing
'enforce making a selection.
If sSelText = "DEFAULT_TXT" Then 'write here the default text of your combobox.
MsgBox "Please select subject from the dropdown menu.", vbCritical, "No selection!"
Else
ActiveDocument.Save
sDocname = ActiveDocument.FullName
If Len(ActiveDocument.Path) = 0 Then
MsgBox "Document is not saved!", vbCritical, "Error!"
GoTo lbl_Exit
End If
On Error Resume Next
Set objOutlook = GetObject(, "Outlook.Application")
If Err <> 0 Then
MsgBox "Outlook is not running."
GoTo lbl_Exit
End If
On Error GoTo 0
Set objOutlookMsg = objOutlook.createitem(0)
With objOutlookMsg 'use the selected item as you wish.
.To = "email#emailaddress.com"
.Cc = ""
.Subject = "Favourite Animal is " & sSelText
.attachments.Add sDocname & "_" & sSelText
Set objInspector = .GetInspector
Set objDoc = objInspector.WordEditor
Set objRange = objDoc.Range(0, 0)
.Display
objRange.Text = "My favourite animal is the " & sSelText
.Send
End With
End If
lbl_Exit:
Set objDoc = Nothing
Set objRange = Nothing
Set objOutlookMsg = Nothing
Set objInspector = Nothing
Set objOutlook = Nothing
End Sub
I have the below code that runs through a folder looking for unread messages from a specific person with a specific subject. The loop is not beginning at the most recent emails. It's beginning a month ago where all the messages are read.
Sub MovingAttachmentsIntoNetworkFolders()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Dim olFolder As Outlook.MAPIFolder
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
Set olFolder = objNS.GetDefaultFolder(olFolderInbox).Folders("Email Subfolder") 'Specify Folder here
On Error GoTo ErrorHandler
For Each Item In olFolder.Items
Debug.Print Item.ReceivedTime
If Item.UnRead = True Then
If TypeOf Item Is Outlook.MailItem Then
Dim oMail As Outlook.MailItem: Set oMail = Item
Debug.Print Item.SenderEmailAddress
Debug.Print Item.Subject
Debug.Print Item.Attachments.Count
If Item.Sender = "emailaddress#email.com" And _
Item.Subject = "EmailSubject" And _
Item.Attachments.Count = 1 Then
'Set folder to save in.
Dim olDestFldr As Outlook.MAPIFolder
Dim myAttachments As Outlook.Attachments
Dim Att As String
'location to save in. Can be root drive or mapped network drive.
Const attPath As String = "mappednetworkdrive"
' save attachment
Set myAttachments = Item.Attachments
Att = myAttachments.Item(1).FileName
Debug.Print Att & "\" & Format(Item.ReceivedTime, "mm-dd-yyyy")
myAttachments.Item(1).SaveAsFile Format(Item.ReceivedTime, "mm.dd.yyyy") & " " & Att
' mark as read
Item.UnRead = False
End If
End If
End If
Next
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
Any reason why my code is behaving this way?
For a For Each loop, you can sort a collection of the items in the folder by ReceivedTime as described here Email data exported to Excel - Sort by Received Date
Note: Untested code to demonstrate how to sort
Option Explicit
Sub MovingAttachmentsIntoNetworkFolders()
Dim objNS As NameSpace
Dim olFolder As Folder
dim objItem as object
dim fldItems as items
Set objNS = GetNamespace("MAPI")
Set olFolder = objNS.GetDefaultFolder(olFolderInbox)
'Specify Folder here
Set olFolder = olFolder.Folders("Email Subfolder")
On Error GoTo ErrorHandler
' https://stackoverflow.com/questions/14948295/email-data-exported-to-excel-sort-by-received-date
set fldItems = olFolder.Items
fldItems.Sort "ReceivedTime", true
For Each objItem In fldItems
Debug.Print objItem.ReceivedTime
If objItem.UnRead = True Then
If TypeOf objItem Is MailItem Then
Debug.Print objItem.SenderEmailAddress
Debug.Print objItem.Subject
Debug.Print objItem.Attachments.Count
If objItem.Sender = "emailaddress#email.com" And _
objItem.Subject = "EmailSubject" And _
objItem.Attachments.Count = 1 Then
' mark as read
objItem.UnRead = False
End If
End If
End If
set objItem = Nothing
Next
ProgramExit:
Set objNS = Nothing
Set olFolder = Nothing
set fldItems = Nothing
set objItem = Nothing
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
If code is in Outlook there is no need to reference Outlook.
Avoid using Item and olMail for variable names as they already have a purpose.
I am trying to send a completed work email containing multiple PDF attachments, I wish send only the PDF files to the recipient and avoid any other atttachments such as excel files or image files only pdf to be forwarded.
P.S. note email may have more than 1 attachments with combination of pdfs, excels, images, however only pdfs have to be forwarded. I'm unable to find how to code that part. please see below my existing code.
Sub Send2Recipient()
' Send Completed Message to Recipient
On Error Resume Next
Dim oApp As Outlook.Application
Dim objFolder As Outlook.MAPIFolder
Set oApp = New Outlook.Application
Set objNS = Application.GetNamespace("MAPI")
Set objInbox = objNS.GetDefaultFolder(olFolderInbox)
Set objFolder = objInbox.Folders("Helpdesk")
Dim oEmail As Outlook.MailItem
Dim strFile As String
Dim sFileType As String
'Require that this procedure be called only when a message is selected
If Application.ActiveExplorer.Selection.Count = 0 Then
Exit Sub
End If
For Each objItem In Application.ActiveExplorer.Selection
If objFolder.DefaultItemType = olMailItem Then
If objItem.Class = olMail Then
Response = MsgBox("Forward message (" + item.Subject + ") to Appended Subject")
Set myforward = objItem.Forward
myforward.Body = "Scan Only"
myforward.Subject = "Scan Only"
myforward.Recipients.Add "DHL.GB01PREV#dhl.com"
myforward.Display
End If
End If
Next
End Sub
Updated VBA script
Sub Send2New()
' Send Completed Message to Accenture
On Error Resume Next
Dim oApp As Outlook.Application
Dim objFolder As Outlook.MAPIFolder
Set oApp = New Outlook.Application
Set objNS = Application.GetNamespace("MAPI")
Set objInbox = objNS.GetDefaultFolder(olFolderInbox)
'Set objFolder = objInbox.Folders("Helpdesk")
Dim oEmail As Outlook.MailItem
Dim strFile As String
Dim sFileType As String
Dim bk, fg As Integer
'Require that this procedure be called only when a message is selected
If Application.ActiveExplorer.Selection.Count = 0 Then
Exit Sub
End If
For Each objItem In Application.ActiveExplorer.Selection
If objFolder.DefaultItemType = olMailItem Then
If objItem.Class = olmail Then
Response = MsgBox("Forward message (" + Item.Subject + ") to Appended Subject")
Set myforward = objItem.Forward
myforward.Body = "Scan Only"
myforward.Subject = "Scan Only"
myforward.Recipients.Add "xyz#abc.com"
myforward.Display
bk = myforward.Attachments.Count
fg = 1
For i = 1 To bk
If InStr(LCase(myforward.Attachments(fg).FileName), ".pdf") = 0 Then
myforward.Attachments(fg).Delete
Else: fg = fg + 1
End If
Next i
End If
End If
Next
End Sub
I have created two macros for you.
The first, Investigate, outputs information about attachments to the Immediate Window. There are four types of attachment. A “standard” attachment is of type “By Value”. I have never seen an OLE attachment and do not know what such an attachment is. I have seen the other types but not for many years.
The second, ForwardEmailsWithoutNonPdfAttachments(), demonstrates the functionality you seek. I have sent emails containing a selection of attachments from my Gmail account to my Outlook account and have used the macro to send them back with the non-PDF attachments deleted. These attachments were all “By Value” attachments. I am not sure what would happen if you tried to forward emails with other types of attachments which is the reason for the first macro. This macro is not very elegant but it demonstrates the techniques necessary to meet your objective.
Option Explicit
Public Sub Investigate()
Dim AttachType As String
Dim Exp As Outlook.Explorer
Dim InxAttach As Long
Dim ItemCrnt As MailItem
Dim NumAttach As Long
Dim NumSelected As Long
Set Exp = Outlook.Application.ActiveExplorer
NumSelected = Exp.Selection.Count
If NumSelected = 0 Then
Debug.Print "No emails selected"
Else
For Each ItemCrnt In Exp.Selection
With ItemCrnt
Debug.Print "From: " & .SenderName & " | Subject: " & .Subject
For InxAttach = 1 To .Attachments.Count
' There are four types of attachment:
' * olByValue 1
' * olByReference 4
' * olEmbeddedItem 5
' * olOLE 6
With .Attachments(InxAttach)
Select Case .Type
Case olByValue
AttachType = "Val"
Case olEmbeddeditem
AttachType = "Ebd"
Case olByReference
AttachType = "Ref"
Case olOLE
AttachType = "OLE"
Case Else
AttachType = "Unk"
End Select
Debug.Print AttachType & " " & .FileName & " | " & .DisplayName
End With ' .Attachments(InxAttach)
Next ' ItemCrnt
End With
Next
End If
End Sub
Sub ForwardEmailsWithoutNonPdfAttachments()
Dim AttachType As String
Dim Exp As Outlook.Explorer
Dim InxAttach As Long
Dim ItemCopy As MailItem
Dim ItemOrig As MailItem
Dim NumAttach As Long
Dim NumSelected As Long
Set Exp = Outlook.Application.ActiveExplorer
NumSelected = Exp.Selection.Count
If NumSelected = 0 Then
Debug.Print "No emails selected"
Else
For Each ItemOrig In Exp.Selection
Set ItemCopy = ItemOrig.Copy
With ItemCopy
.Subject = "FW: " & .Subject
' Delete all original recipients
Do While .Recipients.Count > 0
.Recipients.Remove (1)
Loop
' Add new recipient
.Recipients.Add "tonydallimore23#gmail.com"
If .Attachments.Count > 0 Then
For InxAttach = .Attachments.Count To 1 Step -1
With .Attachments(InxAttach)
' This will stop the macro if an attachment is not a regular attachment
Debug.Assert .Type = olByValue
If LCase(Right$(.FileName, 4)) <> ".pdf" Then
.Delete
End If
End With ' .Attachments(InxAttach)
Next InxAttach
End If
.Send
End With ' ItemCopy
Set ItemCopy = Nothing
Next ItemOrig
End If
End Sub
got a little problem, I hope someone can help me.
(Outlook 2010 VBA)
this is my current code, what i need is when i click on a mail (only the mail i clicked on, not every mail in the folder/same place)
it has to check if the Sender of the mail is already in my contacts or in the
Addressbook 'All Users',
and if it's not a one of those yet, open the AddContact window and fill in his/her information
what doesn't work yet is:
most important of all, it doesn't run the script when i click on a mail
the current check if the contact already exsist doesn't work
and goes with a vbMsgBox (yes or no and response stuff) wich is not what i want/need
if the contact already exsist then nothing has to happen.
I hope i gave enough information and someone can help me out here :)
Sub AddAddressesToContacts(objMail As Outlook.MailItem)
Dim folContacts As Outlook.MAPIFolder
Dim colItems As Outlook.Items
Dim oContact As Outlook.ContactItem
Dim oMail As Outlook.MailItem
Dim obj As Object
Dim oNS As Outlook.NameSpace
''don't want or need a vbBox/ask box, this is a part of the current contactcheck
''wich doesn't work and is totaly wrong :P
Dim response As VbMsgBoxResult
Dim bContinue As Boolean
Dim sSenderName As String
On Error Resume Next
Set oNS = Application.GetNamespace("MAPI")
Set folContacts = oNS.GetDefaultFolder(olFolderContacts)
Set colItems = folContacts.Items
''this selects the mail that is currently selected.
''what i want is that the sender of the new incoming mail gets added to contacts
''(ofcourse, if that contact doesn't exsist yet)
''so the new incoming mail gotta be selected.
For Each obj In Application.ActiveExplorer.Selection
If obj.Class = olMail Then
Set oContact = Nothing
bContinue = True
sSenderName = ""
Set oMail = obj
sSenderName = oMail.SentOnBehalfOfName
If sSenderName = ";" Then
sSenderName = oMail.SenderName
End If
Set oContact = colItems.Find("[FullName] = '" & sSenderName & "'")
''this part till the --- is wrong, i need someting to check if the contact (the sender)
''already exsists. Any ideas?
If Not (oContact Is Nothing) Then
response = vbAbort
If response = vbAbort Then
bContinue = False
End If
End If
''---------
If bContinue Then
Set oContact = colItems.Add(olContactItem)
With oContact
.Email1Address = oMail.SenderEmailAddress
.Email1DisplayName = sSenderName
.Email1AddressType = oMail.SenderEmailType
.FullName = oMail.SenderName
'.Save
oContact.Display
End With
End If
End If
Next
Set folContacts = Nothing
Set colItems = Nothing
Set oContact = Nothing
Set oMail = Nothing
Set obj = Nothing
Set oNS = Nothing
End Sub
hey, i still have a last question,
'sets the name of the contact
Set oContact = colItems.Find("[FullName] = '" & sSenderName & "'")
'checks if the contact exsist, if it does exit the for loop
If Not oContact Is Nothing Then
Exit For
End If
End If
this checks if the name is already in contacts,
i need it that it checks if the E-mailaddress is in contacts or not,
can you help me with that?
i had someting like this in mind
set oSendermail = ?the e-mailaddress?
If Not oSendermail Is Nothing Then
Exit For
End If
End If
A solution (including test routine) could look as follows:
(assuming that we only consider external SMTP mails. Adjust the path to your contact folder and add some more error checking!)
Option Explicit
Private Declare Function GetTickCount Lib "kernel32.dll" () As Long
Sub AutoContactMessageRule(newMail As Outlook.mailItem)
' "script" routine to be called for each incoming Mail message
' This subroutine has to be linked to this mail type using
' Outlook's rule assistant
Dim EntryID As String
Dim StoreID As Variant
Dim mi As Outlook.mailItem
Dim contactFolder As Outlook.Folder
Dim contact As Outlook.ContactItem
On Error GoTo ErrorHandler
' we have to access the new mail via an application reference
' to avoid security warnings
EntryID = newMail.EntryID
StoreID = newMail.Parent.StoreID
Set mi = Application.Session.GetItemFromID(EntryID, StoreID)
With mi
If .SenderEmailType = "SMTP" Then
Set contactFolder = FindFolder("Kemper\_local\TestContacts")
Set contact = contactFolder.items.Find("[Email1Address]=" & Chr(34) & .SenderEmailAddress & Chr(34))
If Not TypeName(contact) <> "Nothing" Then
Set contact = contactFolder.items.Add(olContactItem)
contact.Email1Address = .SenderEmailAddress
contact.Email1AddressType = .SenderEmailType
contact.FullName = .SenderName
contact.Save
End If
End If
End With
Exit Sub
ErrorHandler:
MsgBox Err.Description, vbCritical, "Ooops!"
Err.Clear
On Error GoTo 0
End Sub
Private Function FindFolder(path As String) As Outlook.Folder
' Locate MAPI Folder.
' Separate sub-folder using '/' . Example: "My/2012/Letters"
Dim fd As Outlook.Folder
Dim subPath() As String
Dim I As Integer
Dim ns As NameSpace
Dim s As String
On Error GoTo ErrorHandler
s = Replace(path, "\", "/")
If InStr(s, "//") = 1 Then
s = Mid(s, 3)
End If
subPath = Split(s, "/", -1, 1)
Set ns = Application.GetNamespace("MAPI")
For I = 0 To UBound(subPath)
If I = 0 Then
Set fd = ns.Folders(subPath(0))
Else
Set fd = fd.Folders(subPath(I))
End If
If fd Is Nothing Then
Exit For
End If
Next
Set FindFolder = fd
Exit Function
ErrorHandler:
Set FindFolder = Nothing
End Function
Public Sub TestAutoContactMessageRule()
' Routine to test Mail Handlers AutoContactMessageRule()'
' without incoming mail messages
' select an existing mail before executing this routine
Dim objItem As Object
Dim objMail As Outlook.mailItem
Dim started As Long
For Each objItem In Application.ActiveExplorer.Selection
If TypeName(objItem) = "MailItem" Then
Set objMail = objItem
started = GetTickCount()
AutoContactMessageRule objMail
Debug.Print "elapsed " & (GetTickCount() - started) / 1000# & "s"
End If
Next
End Sub