Forward mail and add content to body (Outlook 2007, VBA) - vba

Can anyone help me with editing the VBA-Code for the following Problem:
I want to forward e-mails with a specific subject to an specific E-Mail. In this process i want to add a text to the forwarded body.
Thank's for your help!
edit.
I have the code now, but it doesn't work properly. It sends the last E-Mail clicked on :(.
Sub Test(oMail As MailItem)
Dim MyItem As Outlook.MailItem
Dim obj_curitem As MailItem
Dim obj_newitem
Dim obj_Selection
Dim obj_curfolder
Dim obj_msgitems
Dim Forward As Object
If Err.Number = 0 Then
Set obj_Selection = Outlook.ActiveExplorer.Selection
If obj_Selection.Count > 0 Then
For Each obj_curitem In obj_Selection
strID = obj_curitem.EntryID
Set olNS = Application.GetNamespace("MAPI")
'Object auf einem neuen Item erstellen
Set obj_newitem = obj_curitem.Forward
With obj_curitem.Forward
.Forward = True
.SentOnBehalfOfName = "###" 'Deine Mailadresse
.Subject = "WG" & .Subject 'Betreff
.To = "###" 'Empfängermail
.BODY = "geprüft" & .BODY 'E-Mail Inhalt
.Send
End With
Next
End If
End If
End Sub

In general you will need to handle the NewMailEx event of the Application class where you can check out the Subject property and decide whether to forward the email or not. The Forward method of the Application class allows you doing so - it executes the Forward action for an item and returns the resulting copy as a MailItem object.
This NewMailEx event fires once for every received item that is processed by Microsoft Outlook. The item can be one of several different item types, for example, MailItem, MeetingItem, or SharingItem. The EntryIDsCollection string contains the Entry ID that corresponds to that item. You can use the Entry ID returned in the EntryIDCollection array to call the NameSpace.GetItemFromID method and process the item.
The Outlook object model provides three main ways for working with item bodies:
Body.
HTMLBody.
The Word editor. The WordEditor property of the Inspector class returns an instance of the Word Document which represents the message body. So, you can use the Word object model do whatever you need with the message body.
See Chapter 17: Working with Item Bodies for more information.

Related

Outlook VBA to format text as HTML , and select a quick parts

I am completely clueless about VBA for outlook. I was hoping that I could record macros, but I see that its not possible.
So the issue I am having is that I receive close to 100 emails daily that arrive in plain text, and I always need to convert to HTML so that I can select a Quick Parts, then send the email.
Can this be automated with VBA?
The MailItem.BodyFormat property allows setting an OlBodyFormat constant indicating the format of the body text. For example:
Sub CreateHTMLMail()
'Creates a new email item and modifies its properties.
Dim objMail As MailItem
'Create mail item
Set objMail = Application.CreateItem(olMailItem)
With objMail
'Set body format to HTML
.BodyFormat = olFormatHTML
.HTMLBody = "<HTML><H2>The body of this message will appear in HTML.</H2><BODY>Type the message text here. </BODY></HTML>"
.Display
End With
End Sub
To handle incoming emails you may use the NewMailEx event of the Application class. The NewMailEx event fires when a new message arrives in the Inbox and before client rule processing occurs. You can use the Entry ID returned in the EntryIDCollection array to call the NameSpace.GetItemFromID method and process the item.

Vba doesn't forward the latest message in the conversation

Set myNameSpace = myOlApp.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myitems = myInbox.Items
For Each myitem In myitems
If myitem.Class = olMail Then
If InStr(1, myitem.Subject, "Hi") > 0 Then
If myitem.Sender.GetExchangeUser.PrimarySmtpAddress = "xyz#abc.com" Then
With myitem.Forward
.Recipients.Add "pqr#abc.com"
.CC = "xyz#abc.com"
.Body = "Hey,there"
.Send
End With
End if
End if
End if
Next myitem
Basically if I got the last email with subject line as "Hi" from xyz then I want to forward it to pqr and CC xyz . Everthing works fine but the forwarded message is not the original one but it just composes a new email. I always want to add something while forwarding an email in addition to what I received from xyz. Can anyone help please. Thanks.
Edit:- If I put a display command immediately after With myitem.Forward it shows the entire thread but it disappears and turns in to a new email once I add the recipient and the body. Also I think that it can interpret .body as the entire new body and I should find something which will add to existing body.
If you need to preserve the existing message you should to insert your text before the existing property value (in case of plain text emails).
.Body = "Hey,there" + .Body
Or inject your HTML markup into the <body> element to keep the HTML markup well-formed.
The Outlook object model provides three main ways for working with item bodies:
Body - a string representing the clear-text body of the Outlook item.
HTMLBody - a string representing the HTML body of the specified item.
Word editor - the Microsoft Word Document Object Model of the message being displayed. The WordEditor property of the Inspector class returns an instance of the Document class from the Word object model which you can use to set up the message body.
You can read more about all these ways in the Chapter 17: Working with Item Bodies. It us up to you which way is to choose to customize the message body.

Getting email body using vba code

I am trying to get the email header and body inside my email in outlook using VBA. I am using the Application_NewMail() event handler to process that new mail has arrived, but I cannot figure out how to get the header and body from there.
This is the code that I have inside the Application_NewMail() event handler:
Private WithEvents myOlItems As Outlook.Items
Private Sub Application_NewMail()
Dim olApp As Outlook.Application
Dim oNS As NameSpace
Dim oFolder As MAPIFolder
Dim oNewMail As MailItem
Set olApp = Outlook.Application
Set oNS = GetNamespace("MAPI")
Set oFolder = oNS.GetDefaultFolder(olFolderInbox)
Set oNewMail = oFolder.Items.GetFirst
'This is the string that hold the mail body.
Dim mailBody As String
Dim mailArg() As String
MsgBox "New Mail!"
End Sub
This function is firing properly once I receive emails. I successfully get the messagebox to pop up. But I want to be able to read the mail body and header to insert into a database.
The actual database side of it I know how to do, but I am unsure how to get the header and body from the email. I have tried something like this:
Set olItem = ActiveExplorer.Selection.Item(1)
mailBody = oNewMail.Body
mailArg = Split(mailBody, vbLf)
'Check to see what is inside the body. We need to say Tank X: Y
MsgBox "This is line one " & mailArg(0) & "This is line two " & mailArg(1)
And I receive the error: Object variable or With block variable not set
Any help will be greatly appreciated.
You need to handle the NewMailEx event of the Application class instead. This event fires once for every received item that is processed by Microsoft Outlook. The item can be one of several different item types, for example, MailItem, MeetingItem, or SharingItem. The EntryIDsCollection string contains the Entry ID that corresponds to that item.
The NewMailEx event fires when a new message arrives in the Inbox and before client rule processing occurs. You can use the Entry ID returned in the EntryIDCollection array to call the NameSpace.GetItemFromID method and process the item.
The Outlook object model provides three main ways for working with item bodies:
Body.
HTMLBody.
The Word editor. The WordEditor property of the Inspector class returns an instance of the Word Document which represents the message body. So, you can use the Word object model do whatever you need with the message body.
Finally, you can use the PropertyAccessor object (see the corresponding property of the MailItem class) to read the "PR_TRANSPORT_MESSAGE_HEADERS" property value.
propertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E")

Outlook 2013: select multiple emails and autoreply using template

I am trying to get this code to work.
I want to select multiple emails from my inbox and send a auto reply using a template.
I am getting a run-time error: Object variable or With Block variable not set.
Any help would be appreciated. Also I would like to add a msg box telling me how many items were sent.
Option Explicit
Sub ReplywithTemplate()
Dim Item As Outlook.MailItem
Dim oRespond As Outlook.MailItem
For Each Item In ActiveExplorer.Selection
' This sends a response back using a template
Set oRespond = Application.CreateItemFromTemplate("C:\Users\Accounting\AppData\Roaming\Microsoft\Templates\scautoreply.oft")
With oRespond
.Recipients.Add Item.SenderEmailAddress
.Subject = Item.Subject
' includes the original message as an attachment
.Attachments.Add Item
' use this for testing, change to .send once you have it working as desired
.Display
End With
On Error Resume Next
Next
Set oRespond = Nothing
End Sub
I have noticed the following lines of code:
For Each oRespond In ActiveExplorer.Selection
' This sends a response back using a template
Set oRespond = Application.CreateItemFromTemplate("C:\Users\Accounting\AppData\Roaming\Microsoft\Templates\scautoreply.oft")
With oRespond
You need to use a new variable for creating an auto-reply email from a template because the selected Outlook item is missed (replaced with a newly created one).
So, basically you can create an item from a template, add recipients from the selected Outlook item and call the Send method. Or you can use the Reply method of the selected item in Outlook, copy the required properties from a template and call the Send method. It is up to you which way is to choose.
Finally, you may find the Getting Started with VBA in Outlook 2010 article helpful.

Forwarding Outlook Item as attachment and adding it to a category in the same VBA macro

I have a macro that works for forwarding multiple Outlook items as attachments. I've pasted that below, but I want it to also add the forwarded message(s) to a category in outlook. So, not only would it forward the items that are in my inbox to the recipient, but it would also mark those items in a certain category. This way I could track which items I have forwarded using the macro. As it is now, it will show me the item has been forwarded on such and such date, but that may have been just a regular forwarding action. Hence the need for the macro to add the item to a specialized category.
Sub ForwardSelectedItems()
On Error Resume Next
Dim objItem As Outlook.MailItem
If Application.ActiveExplorer.Selection.Count = 0 Then
MsgBox ("No item selected")
Exit Sub
End If
For Each objItem In Application.ActiveExplorer.Selection
Set objMsg = objItem.Forward()
With objMsg
.Attachments.Add objItem, olEmbeddeditem
.Subject = "example"
.To = "example#example.com"
.Body = “”
.Send
End With
Next
Set objItem = Nothing
Set objMsg = Nothing
End Sub
The Categories property of the MailItem class allows to set a string representing the categories assigned to the Outlook item. Here is what MSDN states:
Categories is a delimited string of category names that have been assigned to an Outlook item. This property uses the character specified in the value name, sList, under HKEY_CURRENT_USER\Control Panel\International in the Windows registry, as the delimiter for multiple categories. To convert the string of category names to an array of category names, use the Microsoft Visual Basic function Split.
Note, you can use the Categories property of the Namespace class to get a Categories object that represents the set of Category objects available. This property represents the Master Category List, which is the set of Category objects that can be applied to Outlook items contained by the NameSpace object, and applies to all users of that namespace.
Also you may consider specifying the SaveSentMessageFolder for the mail item. The property 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. So, you can easily recognize the auto-forwarded messages.