Send an email and ReplyAll to it - vba

My task is to send an email containing a report and send another email containing another report to the same email thread by way of replying/forwarding to the sent email (excluding some recipients).
Option Explicit
Sub TestReply()
Dim objApp As Application
Dim objNewMail As Outlook.MailItem
Dim objReply As Outlook.MailItem
Set objApp = Outlook.Application
Set objNewMail = objApp.CreateItem(0)
' Outgoing email
With objNewMail
.Subject = "Test sending email"
.To = "abc#abc.com"
.HTMLBody = "This is the outgoing email."
.Send
End With
' Reply email
Set objReply = objNewMail.ReplyAll
With objReply
.HTMLBody = "This is the reply emal."
.Display
End With
Set objApp = Nothing
Set objNewMail = Nothing
Set objReply = Nothing
End Sub
I can't find a way to send the follow up email (either by reply or forward).
When I try the above code, it says error the item is moved/deleted. I guess it is becaused when the email is sent, the objNewMail odject is also terminated.
I tried adding RE: or FW: to the subject of the original email but then the two emails will not be in the same thread but independent emails.
An additional problem is that I have two email accounts in Outlook: my own email and team email and the reports are to be sent from the team email.

You can determine if an item added to the sent folder matches objNewMail.
In ThisOutlookSession
Option Explicit
Private WithEvents sentFolderItems As Items
Private Sub Application_Startup()
'Set sentFolderItems = Session.GetDefaultFolder(olFolderSentMail).Items
' Reference any folder by walking the folder tree
' assuming the team folder is in the navigation pane
Set sentFolderItems = Session.folders("team mailbox name").folders("Sent").Items
End Sub
Private Sub sentFolderItems_ItemAdd(ByVal Item As Object)
Dim myReplyAll As MailItem
If Item.Class = olMail Then
'do not use InStr unless you change some part of words in original subject
' or another reply will be generated
If Item.Subject = "Test sending email" Then
Set myReplyAll = Item.ReplyAll
With myReplyAll
.HTMLBody = "This is the reply email."
.Display
End With
End If
End If
End Sub
Sub TestReply()
Dim objNewMail As MailItem
'Set objNewMail = CreateItem(olMailItem)
' Add, not create, in non-default folder
Set objNewMail = Session.folders("team mailbox name").folders("Inbox").Items.Add
' Outgoing email
With objNewMail
.Subject = "Test sending email"
.To = "abc#abc.com"
.HTMLBody = "This is the outgoing email."
.Send
End With
End Sub
Note: Application. and Outlook. are not needed when code is in Outlook.

Call Send on the original email (objNewMail) only after you construct the reply.

Right so currently your code is doing this:
Creating a mail, sending it.
Trying to reply to the mailitem object which is already sent.
What you need is an event Hook to catch the mail when it's received by yourself. (assuming this is how you're reply all and removing some recipients for report 2)
Here is how you accomplish this:
First Create a WithEvents as Items call AllMyItems, then a hook in the AllMyItems_ItemAdd, then initialize the event when Outlook Starts using Application_Startup (a built in event)
Be very careful to identify criteria for forwarding / actioning the incoming mail item, since this event code will scan every mail sent to your main inbox and evaluate it. IF you want to further reduce the risk of forwarding a mail item to the wrong person, consider using an outlook rule to sort it into a custom folder, and then setting that folder's location as the Set AllMyItems = line instead of default folder
Option Explicit
'for the Default DL inbox
Private WithEvents AllMyItems As 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 myolitems = objNS.GetDefaultFolder(olFolderInbox).Items
'all my items in the main box
Set AllMyItems = objNS.GetDefaultFolder(olFolderInbox).Items
Set olapp = Nothing
Set objNS = Nothing
End Sub
Private Sub AllMyItems_ItemAdd(ByVal Item As Object)
On Error Resume Next
If TypeName(Item) <> "Mailitem" Then
If TypeName(Item) = "ReportItem" Then GoTo 0 'undeliverables shows as a report item
If TypeName(Item) = "MeetingItem" Then GoTo 0
Dim oItem As MailItem
Dim myForward As MailItem
Set oItem = Item
'use the next line to check for a property of the incoming mail, that distinguishes it from other mail, since this event will run on every mail item
If InStr(1, oItem.Subject, "Your public folder is almost full", vbTextCompare) > 0 Then
Set myForward = oItem.Forward
myForward.Recipients.Add "derp#derpinacorp.com"
myForward.Importance = olImportanceHigh
'MsgBox "uno momento"
myForward.Send
Else
End If
Else
End If
0:
End Sub

Related

Control contents of email address fields

I want to send the body of a Word document as an email from MS Word 2016.
I want the user to select recipients from the address book. I want them to only be put in the BCC field.
How do I monitor the to/from/CC/BCC fields for changes, and then move those changes to BCC?
The documentation indicates the use of Inspectors, but nothing specific about accessing the contents of these fields.
I have two approaches:
open a new Outlook mail item, load the contents of the Word file to it, and then try to monitor the fields that way.
send directly from Word using the Quick Access Toolbar option "Send to Mail Recipient".
I don't know if that is an option based on what I was reading and if those fields are accessible via VBA.
Code example of what I have so far:
Sub SendDocumentInMail()
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 = "recipient#mail.com"
'Set the recipient for a copy
.CC = "recipient2#mail.com"
'Set the subject
.Subject = "New subject"
'The content of the document is used as the body for the email
.Body = ActiveDocument.Content
.Send
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
It seems you are interested in the SelectNamesDialog object which displays the Select Names dialog box for the user to select entries from one or more address lists, and returns the selected entries in the collection object specified by the property SelectNamesDialog.Recipients.
The dialog box displayed by SelectNamesDialog.Display is similar to the Select Names dialog box in the Outlook user interface. It observes the size and position settings of the built-in Select Names dialog box. However, its default state does not show Message Recipients above the To, Cc, and Bcc edit boxes.
The following code sample shows how to create a mail item, allow the user to select recipients from the Exchange Global Address List in the Select Names dialog box, and if the user has selected recipients that can be completely resolved, then send the mail item.
Sub SelectRecipients()
Dim oMsg As MailItem
Set oMsg = Application.CreateItem(olMailItem)
Dim oDialog As SelectNamesDialog
Set oDialog = Application.Session.GetSelectNamesDialog
With oDialog
.InitialAddressList = _
Application.Session.GetGlobalAddressList
.Recipients = oMsg.Recipients
If .Display Then
'Recipients Resolved
oMsg.Subject = "Hello"
oMsg.Send
End If
End With
End Sub

Outlook Email created in VBA using a template converts to plain text when saved

Below is the code that I am running in ThisOutlookSession. The code is meant to check all incoming emails and if the email is from a certain email address and contains a specific string in the subject then a new email is created from a template and the triggering email is attached and the email is then sent out to a different email address. This portion all works fine.
Also to note I am using windows 10 and office 2016.
The problem that I am having is the email is converted to plain text unless it is displayed first. The template that I have created is saved as a HTML formatted message. I have tried adding lines such as
NewMsg.BodyFormat = olFormatHTML
NewMsg.save
But this doesn't seem to work as the email that is sent was still in the plain text format. If I add the following to that the message it basically works.
NewMsg.BodyFormat = olFormatRichText
NewMsg.save
NewMsg.BodyFormat = olFormatHTML
NewMsg.save
However the above block of code removes a lot of the formatting that was saved in my template such as different fonts/ font sizes.
Am I missing something about working with templates in VBA?
Also The problem that I am having with displaying the message first is two things. The obvious one is the flash that this causes because the message is briefly displayed. The second is my default signature is also added to the displayed message but I wanted to use a custom signature that I built into my template.
Here is my full code with sensitive information removed.
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")
' default local Inbox
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 NewMsg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
If Msg.SenderEmailAddress <> "example#example.com" Then GoTo Skip
If InStr(1, Msg.Subject, "Specific String") > 0 Then 'checks if subject contains the proper string
Set NewMsg = Application.CreateItemFromTemplate("Template Path")
Msg.Subject = Replace(Msg.Subject, "Old Subject", "New subject")
Msg.Save
NewMsg.HTMLBody = NewMsg.HTMLBody
NewMsg.Attachments.Add Msg
NewMsg.Recipients.Add("Example#Example.com")
NewMsg.Subject = Msg.Subject
NewMsg.Save
NewMsg.Send
End If
End If
Skip:
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
End Sub
Reset the HTMLBody property - that will force HTML format:
Msg.HTMLBody = Msg.HTMLBody

vba delete email from sent folder

I want to delete an email from the Sent Items folder after the email is forwarded with a rule.
I tried to use "brettdj" code from another post:Macro to delete an email but it's not working for me at all .
what I'm looking for it's a vba macro that can delete an email when you run the script with the rule.
any idea how I can accomplished that
thanks in advance
You don't have a corresponding entry in your contacts folder (address book). The Add method of the Recipients class accepts the name of the recipient; it can be a string representing the display name, the alias, or the full SMTP e-mail address of the recipient.
Sub forwardEmail(itm As Outlook.MailItem)
Dim oExplorer As Outlook.Explorer
Dim oMail As Outlook.MailItem
Dim oOldMail As Outlook.MailItem
Set oExplorer = Application.ActiveExplorer
If oExplorer.Selection.Item(1).Class = olMail Then
Set oOldMail = oExplorer.Selection.Item(1)
Set oMail = oOldMail.Forward
oMail.Recipients.Add "test#gmail.com"
oMail.Recipients.Item(1).Resolve
If oMail.Recipients.Item(1).Resolved Then
'delete forwarded email from sent items
oMail.DeleteAfterSubmit = True
oMail.Send
'delete original email from inbox
'oOldMail.Delete
Else
MsgBox "Could not resolve " & oMail.Recipients.Item(1).Name
End If
Else
MsgBox "Not a mail item"
End If
End Sub

Outlook 2003 VB Script to create forwarding rule

Hello does anyone know how to create a VB Script that will add a rule in Outlook 2003 such that if I receive an email from user PersonA#mail.com it will forward that email to PersonB#mail.com.
I would also like to know if it possible to create a VB Script to remove the previously created rule.
I've done a little research and it seems possible to create a macro to do this, but I am completely lost as I am not familiar with the objects I need to be editing or have any sort of API.
Maybe I have to create a Macro to add the rules and this use a VB script to fire the Macro.
I would use straight VBA instead. The ItemAdd Event can be used to check your default Inbox for incoming messages and forward them. It is simple to edit the email addresses if you need to change the forwarding.
Ex:
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 newMsg As Outlook.MailItem
Dim recip As Outlook.Recipient
' *****************
' edit these to change forwarding rules
' *****************
Const INCOMING_EMAIL As String = "Persion#mail.com"
Const OUTGOING_EMAIL As String = "PersonB#mail.com"
If TypeName(item) = "MailItem" Then
Set Msg = item
If Msg.SenderEmailAddress = INCOMING_EMAIL Then
Set newMsg = Msg.Forward
With newMsg
Set recip = .Recipients.Add OUTGOING_EMAIL
recip.Type = olTo
.Send
End With
' *****************
' perhaps a msgbox?
' MsgBox "Message forwarded", vbInformation
' *****************
End If
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
This code should be placed in ThisOutlookSession module, then you must restart Outlook. If you need placement assistance see Where do I put my Outlook VBA code?

outlook macro to send email conditionally

Could anyone guide me in creating an Outlook Macro that does the following:
Whenever I send a mail to a particular mail-id an automated mail will be send to a specified group pa mail-ids or some outlook contacts group.
Thanks in advance!!
Here is a quick piece of VBA for you to get going with, add it in your ThisOutlookSession module.
you should be able to do the CC via a rule as well from the tools menu, or write the code to create a rule !
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
If Item.MessageClass = "IPM.Note" Then
For Each myRecipient In Item.Recipients
If myRecipient.Address = "<EMAIL ADDRESS TO FIND>" Then
''SendNotification
SendNotificationWithCopy Item
End If
Next
End If
End Sub
Sub SendNotification()
Set objMail = Application.CreateItem(olMailItem)
objMail.Recipients.Add "<EMAIL ADDRESS/GROUP TO SEND NOTIFICATION>"
objMail.Recipients.ResolveAll
objMail.Subject = "NOTIFICATION"
objMail.Body = "Body Text"
objMail.Send
End Sub
Sub SendNotificationWithCopy(obj As Object)
Set objMail = Application.CreateItem(olMailItem)
objMail.Recipients.Add "<EMAIL ADDRESS TO SEND NOTIFICATION>"
objMail.Recipients.ResolveAll
objMail.Attachments.Add obj, OlAttachmentType.olEmbeddeditem
objMail.Subject = "NOTIFICATION with attachment"
objMail.Body = "Body Text"
objMail.Send
End Sub