Outlook reply to multiple emails on demand - vba

Just wondering if this is possible and if it is can someone assist me with?
In this scenario what we do is emails comes into shared folder. We will then have those email sorted.
After the sorting we will start putting emails into an approved folder. What I will like to do is have a VBA macro in outlook that will be able to generate a custom reply to all the emails in the approved folder.
For example if we place 5 emails in the folder and run a script it should send emails out to those 5 senders.
The email will be something generic such as "You are approved, please logout a "time".

I'd suggest starting from the Getting Started with VBA in Outlook 2010 article in MSDN. It explains the basics of programming VBA macros.
The ItemAdd event is fired when one or more items are added to the Items collection (i.e. folder). Be aware, the event is not fired when a large number of items are added to the folder at once.
So, you can handle the ItemAdd event of the approved folder to create and send a reply. The Reply method of Outlook items creates a reply, pre-addressed to the original sender, from the original message. The Send method sends the e-mail message. For example:
Public WithEvents myOlItems As Outlook.Items
Public Sub Initialize_handler()
Set myOlItems = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderContacts).Items
End Sub
Private Sub myOlItems_ItemAdd(ByVal Item As Object)
Dim myOlMItem As Outlook.MailItem
Dim myOlAtts As Outlook.Attachments
Set myOlMItem = myOlApp.CreateItem(olMailItem)
myOlMItem.Save
Set myOlAtts = myOlMItem.Attachments
' Add new contact to attachments in mail message
myOlAtts.Add Item, olByValue
myOlMItem.To = "Sales Team"
myOlMItem.Subject = "New contact"
myOlMItem.Send
End Sub

Outlook reply to multiple emails on demand
Paste the following code in "ThisOutlookSession"
Outlook will automatically send a reply when you move Emails to "approved" folder
Option Explicit
'// items in the target folder to events
Dim WithEvents TargetFolderItems As Items
Private Sub Application_Startup()
Dim olNamespace As Outlook.NameSpace
Set olNamespace = Application.GetNamespace("MAPI")
Set TargetFolderItems = olNamespace.GetDefaultFolder(olFolderInbox) _
'// Set your folder here
.Folders.Item("approved").Items
End Sub
'// ItemAdd event code
Sub TargetFolderItems_ItemAdd(ByVal Item As Object)
Dim olReply As MailItem
Set olReply = Item.Reply
olReply.HTMLBody = "You are approved " & vbCrLf & olReply.HTMLBody
olReply.Send
Set TargetFolderItems = Nothing
Set olReply = Nothing
End Sub

Related

Vb.net Outlook pick first in sent mail folder getfirst from last weeks items instead of the first item

In my Outlook addin a sub is run when an item is added to the sent mail folder. this item is then archived to a user defined folder (which is done when the mail items opens). In the code below it shows how I get the first items in the send item folder.
Public Sub mySentItems_ItemAdd() Handles mySentItems.ItemAdd
'variables
Dim AppOutlook As New Outlook.Application
Dim ns As Outlook.NameSpace = AppOutlook.Session
Dim siFolder As Outlook.Folder = CType(ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail), Outlook.Folder)
'load the newly added mail as mailitem
Dim mailitem As MailItem = siFolder.Items.GetFirst
MsgBox(mailitem.Subject.ToString)
End Sub
It worked fine a few weeks ago but now it doesnt get the first item in the folder, instead it gets the first item in the folder from the sub folder "Last week". In the image below the item I get is marked with yellow, the item I want is underlined with a black line. does anyone know how I can solve this problem?
Ok I figured it out, the last added item is not the first item in the list but the last item so instead of:
Dim mailitem As MailItem = siFolder.Items.GetFirst
I needed to use
Dim mailitem As MailItem = siFolder.Items.GetLast
First of all, there is no need to create a new Outlook Application instance:
Dim AppOutlook As New Outlook.Application
Instead, you should use the Application property of your add-in class.
Anyway, the Items.ItemAdd event provides an argument which represents an item added to the folder.
Public WithEvents myOlItems As Outlook.Items
Public Sub Initialize_handler()
Set myOlItems = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderContacts).Items
End Sub
Private Sub myOlItems_ItemAdd(ByVal Item As Object)
Dim myOlMItem As Outlook.MailItem
Dim myOlAtts As Outlook.Attachments
Set myOlMItem = myOlApp.CreateItem(olMailItem)
myOlMItem.Save
Set myOlAtts = myOlMItem.Attachments
' Add new contact to attachments in mail message
myOlAtts.Add Item, olByValue
myOlMItem.To = "Sales Team"
myOlMItem.Subject = "New contact"
myOlMItem.Send
End Sub

Trigger an Outlook script after the email has entered the inbox

I'm trying to finalize an integration between my access system and Outlook.
The basis of the system is that Outlook needs to trigger a script when an email enters a specific Inbox. This script then opens the Access DB and runs it's own function to go through that inbox, take the attachment in the email and import it into the database.
Currently both scripts "Work" in so far as Outlook calling Access and Access doing it's thing. The problem is when Outlook executes the script, it's BEFORE the message is actually in the mailbox. The access app will launch, scan the inbox as empty and close just before the message actually enters the inbox.
I've tried adding a "Pause" loop in the script, to try and have it wait until the email is readable before opening the access app, but that just froze outlook for the duration of the "Pause" instead of letting the email become readable.
Here is my script in Outlook:
Sub ExecuteDealRequest(item As Outlook.MailItem)
Dim currenttime As Date
currenttime = Now
Do Until currenttime + TimeValue("00:00:30") <= Now
Loop
Dim AccessApp As Access.Application
Set AccessApp = CreateObject("Access.Application")
AccessApp.OpenCurrentDatabase ("C:\commHU\Comm HU Request.accdb"), False
AccessApp.Visible = True
AccessApp.DoCmd.RunMacro "Macro1"
Set AccessApp = Nothing
End Sub
At this point: I'm using outlook rules to launch the script:
Apply this rule after the message arrives
With Pricing Request in the Subject
and on this computer only
Move it to the Pricing Requests folder
and run Project.ExecuteDealRequest
and stop processing more rules
Any help would be great, as this is the last piece that I need to get working
You don't need Rule, Try it this way- code in ThisOutlookSession
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olNs As Outlook.NameSpace
Dim Inbox As Outlook.MAPIFolder
Set olNs = Application.GetNamespace("MAPI")
Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
Set Items = Inbox.Items
End Sub
Private Sub Items_ItemAdd(ByVal Item As Object)
If TypeOf item Is Outlook.MailItem Then
ExecuteDealRequest Item
End If
End Sub
' ---- Your Code
Sub ExecuteDealRequest(Item As Outlook.MailItem)
Dim currenttime As Date
Dim AccessApp As Access.Application
Set AccessApp = CreateObject("Access.Application")
AccessApp.OpenCurrentDatabase ("C:\commHU\Comm HU Request.accdb"), False
AccessApp.Visible = True
AccessApp.DoCmd.RunMacro "Macro1"
Set AccessApp = Nothing
End Sub
You could try something like this,
Add this code to wait for a new email
Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
ThisOutlookSession.GetNamespace("MAPI").GetItemFromID(EntryIDCollection).Subject
' Check for the email subject / any property
'then call your method
End Sub

How to automatically run a macro on opening a draft in Outlook? (add a BCC)

I'm trying to automatically achieve this workflow:
when user opens a message draft in Outlook (a generated EML file)
if the subject matches a string (immutable, known beforehand, I can't change it; it's something like xyžřy, note the non-ASCII characters):
then add an e-mail to BCC field (immutable, known beforehand, valid e-mail address; let's say it's baz#example.com)
I already know the last part - how to add a BCC to a message, and I use InStr for matching:
Sub addbcc()
Dim objRecip As Recipient
Set oMsg = Application.ActiveInspector.CurrentItem
With oMsg
If InStr(1, oMsg.Subject, "xyžřy") > 0 Then
Set objRecip = oMsg.Recipients.Add("baz#example.com")
objRecip.Type = olBCC
objRecip.Resolve
End If
End With
Set oMsg = Nothing
End Sub
However, the user still needs to remember to press a button to run this macro, which is not more convenient than typing the BCC manually. Is it possible to run the macro automatically when this e-mail is opened?
Is it possible to run the macro automatically when this e-mail is opened?
Work with NewInspector Event , Events occurs when new window is opened by user or through your code.
Example
Option Explicit
Private WithEvents Inspectors As Outlook.Inspectors
Private Sub Application_Startup()
Initialize_handler
End Sub
Public Sub Initialize_handler()
Set Inspectors = Application.Inspectors
End Sub
Private Sub Inspectors_NewInspector(ByVal Inspector As Outlook.Inspector)
If Inspector.currentItem.Class = olMail Then
If Inspector.currentItem.Parent = "Drafts" Then ' Drafts Folder
Debug.Print Inspector.currentItem.Subject ' Immediate Window
' Call Your Code
' Inspector.currentItem.BCC = "baz#example.com"
End If
End If
End Sub
CurrentItem Property
You could monitor the drafts folder with ItemAdd. See the idea here for the inbox. How do I trigger a macro to run after a new mail is received in Outlook?
You could add the bcc in ItemSend. Outlook 2010 - VBA - Set bcc in ItemSend

Outlook VBA move mail in subfolder which hods mail of same subject

I'd like to do the following:
On the event of receiving a new mail the subject of the mail should be checked and if the same subject exists already in any subfolder the mail shall be moved to that same subfolder. In case the same mail can't be found it shall remain in the normal inbox folder.
The target folder as such has no logical connection to the mail, so it is not called like the mail or the mail sender or something like that. It is only the folder which holds one or mails with the same subject.
I managed - by browsing through this forum - to identify the event, the subject of the mail and to perform the actual move.
What I did not manage is:
1. to create a search logic to find already existing mails with the same subject in any folder
2.to return the found folder to use it as the target destination.
This is how it looks up till now and it manages to show a message...
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub Items_ItemAdd(ByVal Item As Object)
On Error GoTo ErrorHandler
Dim Msg As Outlook.MailItem
Dim MoveToFolder As Outlook.MAPIFolder
If TypeName(Item) = "MailItem" Then
Set Msg = Item
MsgBox "Here the folder must be found for '" & Msg.Subject & "'."
'Msg.Move MoveToFolder
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
On top: Is there a specific smart way to do the same on other events like for example "SentMails"?
Thanks a lot for any support.
Ralf
You can use the AdvancedSearch method of the Application class which performs a search based on a specified DAV Searching and Locating (DASL) search string. You can read more about that method in the Advanced search in Outlook programmatically: C#, VB.NET article. So, you can find items with the same subject and then get their Parent property value which stands for the folder where they are stored.
Public blnSearchComp As Boolean
Private Sub Application_AdvancedSearchComplete(ByVal SearchObject As Search)
Debug.Print "The AdvancedSearchComplete Event fired"
If SearchObject.Tag = "Test" Then
m_SearchComplete = True
End If
End Sub
Sub TestAdvancedSearchComplete()
Dim sch As Outlook.Search
Dim rsts As Outlook.Results
Dim i As Integer
blnSearchComp = False
Const strF As String = "urn:schemas:mailheader:subject = 'Test'"
Const strS As String = "Inbox"
Set sch = Application.AdvancedSearch(strS, strF, “Test”)
While blnSearchComp = False
DoEvents
Wend
Set rsts = sch.Results
For i = 1 To rsts.Count
Debug.Print rsts.Item(i).SenderName
Next
End Sub
Is there a specific smart way to do the same on other events like for example "SentMails"?
You may consider handling the ItemSend event of the Application class which is fired whenever an Microsoft Outlook item is sent, either by the user through an Inspector (before the inspector is closed, but after the user clicks the Send button) or when the Send method for an Outlook item. In the event handler you can set the SaveSentMessageFolder property which allows to set a Folder object that represents the folder in which a copy of the e-mail message will be saved after being sent.

Error with Outlook VBA script applied to rule

I have a rule in Outlook which sends a daily email into a particular folder. I then have a VBA script which upon noticing a new unread message in that folder goes in and saves the attachment to a folder on my hard drive and does a few other formatting type things (on the attachment).
I then just linked up the script to the rule in the Outlook rules wizard so it runs as a package.
The problem is as follows: the script is kicked off BEFORE the message is sorted into the appropriate folder. In reality it should run after the message is sorted (otherwise there is nothing for it to act upon). Any ideas on how to rectify?
The code currently begins as follows:
sub saveattachment()
Should it be this instead?
private sub saveattachment()
or
public sub saveattachment()
Would it be better to have the "rule" embedded in the macro instead and then just run it as a private sub anytime the daily email appears in my Inbox?
If you need to assign a VBA macro sub to the Outlook rule, the VBA sub should look like the following one:
Public Sub Test(mail as MailItem)
' your code goes there
End Sub
An instance of the MailItem class is passed as a parameter and stands for the email arrived to the Inbox.
But in case if you need to be sure that your code is triggered when a mail is moved to a particular folder you need to handle the ItemAdd event of the Items class which comes from that folder. Be aware, the event is not fired when more than 16 items are added to the folder simultaneously.
Public WithEvents myOlItems As Outlook.Items
Public Sub Initialize_handler()
Set myOlItems = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderContacts).Items
End Sub
Private Sub myOlItems_ItemAdd(ByVal Item As Object)
Dim myOlMItem As Outlook.MailItem
Dim myOlAtts As Outlook.Attachments
Set myOlMItem = myOlApp.CreateItem(olMailItem)
myOlMItem.Save
Set myOlAtts = myOlMItem.Attachments
' Add new contact to attachments in mail message
myOlAtts.Add Item, olByValue
myOlMItem.To = "Sales Team"
myOlMItem.Subject = "New contact"
myOlMItem.Send
End Sub
Finally, you may find the Getting Started with VBA in Outlook 2010 article helpful.