Outlook 2003: Connect IMAP server with VBA - vba

Sometimes Outlook (2003) loses the connection to one or more IMAP server. With VBA scripts that are supposed to move mails to these mailboxes, for example, I get this error message:
"Runtime error '-972759285 (c604df0b)':
Connection to server is unavailable. Outlook must be online or connected to complete this operation."
I then first have to click on "File" - "Connect to [MAILBOX...]" to establish this connection manually.
I am looking for a VBA solution to automatically connect to multiple mailboxes (IMAP only), but I don't know what to look for in VBA references.
I tried this:
Sub MyTest()
Dim myNameSpace As Outlook.NameSpace
Set myNameSpace = Application.GetNamespace("MAPI")
Set Application.ActiveExplorer.CurrentFolder = myNameSpace.Folders("C-Interessenten").Folders("Interessenten")
Set myNameSpace = Nothing
End Sub
or this
Sub IsOLOffline()
'Determines whether Outlook is currently offline.
Dim myOlApp As Outlook.Application
Dim myNameSpace As Outlook.NameSpace
Set myOlApp = New Outlook.Application
Set myNameSpace = myOlApp.GetNamespace("MAPI")
Debug.Print myNameSpace.Offline
End Sub
Thank you for an idea.

The Outlook object model doesn't provide anything for that out of the box.
The Offline property of the Namespace class returns valid information only for an Exchange profile. It's not intended for non-Exchange account types such as POP3, IMAPI, and HTTP.
You may try to use SyncObjects property of the Namespace class. It returns a set of SyncObject objects representing the Send/Receive groups for a user.
The OnError event is fired when Microsoft Outlook encounters an error while synchronizing a user's folders using the specified Send\Receive group. So, it could help with detecting such cases and then initiating a new sync.
Public WithEvents mySync As Outlook.SyncObject
Sub Initialize_handler()
Set mySync = Application.Session.SyncObjects.Item(1)
mySync.Start
mySync.Stop
End Sub
Private Sub mySync_OnError(ByVal Code As Long, ByVal Description As String)
MsgBox "Unexpected sync error" & Code & ": " & Description
End Sub
A Send\Receive group lets users configure different synchronization scenarios, selecting which folders and which filters apply.
Use the Item method to retrieve the SyncObject object from a SyncObjects object. Because the Name property is the default property of the SyncObject object, you can identify the group by name.

Thank you for the food for thought. I have already experimented a bit by creating a separate group for each IMAP mailbox. Testing is taking a long time because the connections only break sporadically and I can't trigger the break manually. Nevertheless, I have more and more the impression that the SyncObject does not lead to a solution. Thanks anyway.
Is there perhaps the possibility to call the menu item "File" - "Connect to xxx" via vba, for example via FindControl()?

Related

Stop multiple PCs running same script for generic mailbox

I made a script to auto forward messages (with custom response) and, from what i gathered, it has to be on a running Outlook for it to be working.
The issue is that if a couple of machines are running that script will it "go off" multiple times?
from specific sender
containing XYZ in subject
except when it contains ABC in subject
Public Sub FW(olItem As Outlook.MailItem)
Dim olForward As Outlook.MailItem
Set olForward = olItem.Forward
With olForward
'Stuff happens here that work properly
End With
End If
'// Clean up
Set olItem = Nothing
Set olForward = Nothing
End Sub
As #Barney comment is absolutely correct and multiple runs of the script will trigger multiple forward of the item, I would like to add what you should do to perform your action once.
In the script right after successful forward of the message you should add a custom property into the item. The property will just indicate that the message was already forwarded (may be parsed/touched by your script). Now make the condition for entire item handling and check this property exists. If it does, do not perform any actions. The following resource will help with custom properties: How To: Add a custom property to the UserProperties collection of an Outlook e-mail item

Outlook code is working when manually called but giving trouble from Application_ItemSend

I have a code that checks the recipient of the mail, looks what organization is set in the address book for the recipient and dependent on that sets the "SentOnBehalfOfName"-property of the item. If the recipient is working for client2, he will get the mail from "we_love_to_serve_client2#domain.com".
I call the code either before sending the mail via a button in my ribbon, that calls this Sub:
Sub Signatur()
Dim olApp As Outlook.Application
Dim objMail As Outlook.MailItem
Set olApp = Outlook.Application
Set objMail = Application.ActiveInspector.CurrentItem
Call Signatur_auto(objMail)
End Sub
I do this if I want to know which mail-adress is going to be chosen.
In the itemSend-section of thisOutlookSession I also call the same sub
Call Signatur_auto(Item)
Part of the Signatur_auto (i do not copy that in, the question is too long already...) is dealing with the SentOnBehalfOfName-property, the other part is putting the item into the right folder. The Folder is chosen depending on the SentOnBehalfOfName-property.
Now comes the interesting part: Although the folder-part is always working (which can only be when the SentOnBehalfOfName has worked before), the SentOnBehalfOfName only works "half". In the preview-line the mail sent is shown as from "we_serve_client2#domain.com", but when I open the mail it says it was sent by me. The Client always only sees my address, and also answers to my address - which I do not want....
How cant be, that the same code is having different results dependent on where it is called? Is it a Problem to change the sendonbehalf-field in the item send-section?
Thanks for any Inputs!
Max
Why it does not work?
Try this in ItemSend.
Dim copiedItem As mailItem
Set copiedItem = Item.Copy
copiedItem.SentOnBehalfOfName = "we_love_to_serve_client2#domain.com"
copiedItem.Send
Item.delete
Cancel = True ' In case your setup generates an error message as described in the comments
Why it works? Appears "copiedItem.Send" bypasses ItemSend.

How do I make Outlook purge a folder automatically when anything arrives in it?

I hope it's okay to ask this kind of question. Attempting to write the code myself is completely beyond me at the moment.
I need a macro for Outlook 2007 that will permanently delete all content of the Sent Items folder whenever anything arrives in it. Is it possible? How do I set everything up so that the user doesn't ever have to click anything to run it?
I know I'm asking for a fish, and I'm embarrassed, but I really need the thing...
edit:
I've pasted this into the VBA editor, into a new module:
Public Sub EmptySentEmailFolder()
Dim outApp As Outlook.Application
Dim sentFolder As Outlook.MAPIFolder
Dim item As Object
Dim entryID As String
Set outApp = CreateObject("outlook.application")
Set sentFolder = outApp.GetNamespace("MAPI").GetDefaultFolder(olFolderSentMail)
For i = sentFolder.Items.Count To 1 Step -1
sentFolder.Items(i).Delete '' Delete from mail folder
Next
Set item = Nothing
Set sentFolder = Nothing
Set outApp = Nothing
End Sub
It's just a slightly modified version of a piece of code I found somewhere on this site deleting Deleted Items. It does delete the Sent Items folder when I run it. Could you please help me modify it in such a way that it deletes Sent Items whenever anything appears in the folder, and in such a way that the user doesn't have to click anything to run it? I need it to be a completely automated process.
edit 2: Please if you think there's a better tool to achieve this than VBA, don't hesitate to edit the tags and comment.
edit 3: I did something that works sometimes, but sometimes it doesn't. And it's ridiculously complicated. I set a rule that ccs every sent email with an attachment to me. Another rule runs the following code, when an email from me arrives.
Sub Del(item As Outlook.MailItem)
Call EmptySentEmailFolder
End Sub
The thing has three behaviors, and I haven't been able to determine what triggers which behavior. Sometimes the thing does purge the Sent Items folder. Sometimes it does nothing. Sometimes the second rule gives the "operation failed" error message.
The idea of acting whenever something comes from my address is non-optimal for reasons that I'll omit for the sake of brevity. I tried to replace it with reports. I made a rule that sends a delivery report whenever I send an email. Then another rule runs the code upon receipt of the report. However, this has just one behavior: it never does anything.
Both ideas are so complicated that anything could go wrong really, and I'm having trouble debugging them. Both are non-optimal solutions too.
Would this be an acceptable solution? Sorry its late but my copy of Outlook was broken.
When you enter the Outlook VB Editor, the Project Explorer will be on the left. Click Ctrl+R if it isn't. It will look something like this:
+ Project1 (VbaProject.OTM)
or
- Project1 (VbaProject.OTM)
+ Microsoft Office Outlook Objects
+ Forms
+ Modules
"Forms" will be missing if you do not have any user forms. It is possible "Modules" is expanded. Click +s as necessary to get "Microsoft Office Outlook Objects" expanded:
- Project1 (VbaProject.OTM)
- Microsoft Office Outlook Objects
ThisOutlookSession
+ Forms
+ Modules
Click ThisOutlookSession. The module area will turn white unless you have already used this code area. This area is like a module but have additional privileges. Copy this code to that area:
Private Sub Application_MAPILogonComplete()
' This event routine is called automatically when a user has completed log in.
Dim sentFolder As Outlook.MAPIFolder
Dim entryID As String
Dim i As Long
Set sentFolder = CreateObject("Outlook.Application"). _
GetNamespace("MAPI").GetDefaultFolder(olFolderSentMail)
For i = sentFolder.Items.Count To 1 Step -1
sentFolder.Items(i).Delete ' Move to Deleted Items
Next
Set sentFolder = Nothing
End Sub
I have taken your code, tidied it up a little and placed it within an event routine. An event routine is automatically called when the appropriate event occurs. This routine is called when the user has completed their log in. This is not what you requested but it might be an acceptable compromise.
Suggestion 2
I have not tried an ItemAdd event routine on the Sent Items folder before although I have used it with the Inbox. According to my limited testing, deleting the sent item does not interfere with the sending.
This code belongs in "ThisOutlookSession".
Option Explicit
Public WithEvents MyNewItems As Outlook.Items
Private Sub Application_MAPILogonComplete()
Dim NS As NameSpace
Set NS = CreateObject("Outlook.Application").GetNamespace("MAPI")
With NS
Set MyNewItems = NS.GetDefaultFolder(olFolderSentMail).Items
End With
End Sub
Private Sub myNewItems_ItemAdd(ByVal Item As Object)
Debug.Print "--------------------"
Debug.Print "Item added to Sent folder"
Debug.Print "Subject: " & Item.Subject
Item.Delete ' Move to Deleted Items
Debug.Print "Moved to Deleted Items"
End Sub
The Debug.Print statements show you have limited access to the sent item. If you try to access more sensitive properties, you will trigger a warning to the user that a macro is assessing emails.

Runtime Error with the NS.GetSharedDefaultFolder Method

Running it from MS Access (2007) via the Outlook Interop library. I get the error -2147221219 (8004011d) from the starred line on one user account, but not on another. Error appears to be related to permissions, and both accounts have Full Access permissions to the account who's calendar I'm trying to open and can open and create appointments to it via Outlook. Sample code
Public Function NewApt(MtgDate As Date, Cat As String)
Dim objOLApp As Outlook.Application
Dim objNS As Outlook.Namespace
Dim objCalendar As Outlook.Folder
Dim NewMtg As Outlook.AppointmentItem
Dim Org As Outlook.Recipient
Set objOLApp = New Outlook.Application
Set objNS = objOLApp.GetNamespace("MAPI")
Set Org = objNS.CreateRecipient("tuser#somewhere.com")
Org.Resolve
If Org.Resolved Then
** Set objCalendar = objNS.GetSharedDefaultFolder(Org, olFolderCalendar)
Else
MsgBox "Scheduling User failed to resolve, see Crimius."
Exit Function
End If
...
Any ideas why?
I know one reason why this error may appear.
Whe you use the GetSharedDefaultFolder method and the recipient in parameter 1 (Recipient) is hidden from the global address list such an error can occur:
COMException (0x8004011D):
The operation failed because of a registry or installation problem. Restart Outlook and try again. If the problem persists, reinstall.
Maybe, the Outlook-Datafile is protected by password.
Switch to Outlook, enter the Password for the Outlook-Container, and then try again.
I had exactly the same issue. A VBA module that ran during years suddenly refused to. After verification it turned out that the internal e-mail addresses changed to previous runs of the macro...
Changing to email addresses solved the problem.

Move Outlook messages if content contains a number greater than threshold

I get thousands of Nagios alerts in my inbox daily, but many of them are actually trivial (even though Nagios reports them as critical). I want to check whether the text of these alerts contains numbers above a certain threshold; if the numbers are lower than that threshold, move the message to a junk folder. I should really work with my sysadmin to decrease the number of useless alerts Nagios sends in the first place, but humor me in my attempt at a creative workaround.
I'm using Outlook 2007 and have found several tutorials on writing Outlook macros in VB, including this one about programmatically creating a rule to move messages to different folders. That example uses a TextRuleCondition to check whether the subject contains any of the keywords in an array.
But I don't want to check for keywords, I want to check if a number in the message text is greater or less than a threshold value. For example, if the text of a message contains the following, it could be moved to a junk folder:
Nagios bad condition: foo = 3
But if a message contained this, I would want to keep it:
Nagios bad condition: foo = 157
This example seems a little more like what I want in terms of searching the content of the message for arbitrary text. But it requires the message to be open, so I'm not quite sure how to translate it into a rule. Any help would be appreciated.
The second example you link to will put you on the right track to write code that discriminates between good and junk e-mails.
Then you will want to put that code in the _ItemAdd event for the Inbox items, such that it runs every time something new pops up in your Inbox. Here's an example of what should go in your Outlook VBA module:
Public WithEvents myOlItems As Outlook.Items
Public Sub Application_Startup()
' Upon starting Outlook, set reference to the items in the Inbox.
Set myOlItems = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub myOlItems_ItemAdd(ByVal Item As Object)
' Because myOlItems is declared "WithEvents",
' the ItemAdd event will fire anytime something new pops up in the Inbox.
If TypeName(Item) = "MailItem" Then
' It's an e-mail.
' Here goes the code to test whether it should go to the junk folder.
Else
' It's something else than an e-mail.
' Do nothing.
End If
End Sub
JFC has already given you one way. Here is another using RULES to check messages as they arrive. Do this.
Open VBA Editor and paste this code in ThisOutlookSession
UNTESTED
Option Explicit
Sub Sample(MyMail As MailItem)
Dim strID As String, olNS As Outlook.NameSpace
Dim objInboxFolder As Outlook.MAPIFolder
Dim objDestinationFolder As Outlook.MAPIFolder
Dim olMail As Outlook.MailItem
Dim strFileName As String, strSubj As String
Dim Myarray() As String
Dim ThrsdVal As Long
strID = MyMail.EntryID
Set olNS = Application.GetNamespace("MAPI")
Set olMail = olNS.GetItemFromID(strID)
'~~> Email Subject
strSubj = olMail.Subject
'~~> Threshold value
ThrsdVal = 100
'Nagios bad condition: foo = 3
Myarray = Split(strSubj, "=")
Set objInboxFolder = olNS.GetDefaultFolder(olFolderInbox)
'~~> Destination folder
Set objDestinationFolder = objInboxFolder.Folders("Temp")
'~~> Check if less than threshold value
If Val(Trim(Myarray(1))) < ThrsdVal Then
olMail.Move objDestinationFolder
End If
Set olMail = Nothing
Set olNS = Nothing
End Sub
Now
1) Create a new Rule (Select "Check Messages When they Arrive")
2) In (Condition) select "From people or Distribution List"
3) Select the relevant email address from which you are getting the emails
4) In Actions, select "run a script" and then choose the above script.
5) Finally click on Finish and you are done :)
The best part about this is that you can run this rule for existing emails in your inbox folder as well :)
NOTE: Like I mentioned above, I have not tested the code so do let me know if you get any errors and I will rectify it. Also I am assuming that the message will have a subject with the format as "Nagios bad condition: foo = X". I have not included any error handling. I am sure you can take care of that :)
HTH
Sid