Convert Appointment to Email and send - vba

I'm trying to convert an incoming appointment message to email and send.
Public Sub ConvertMeetingToEmail(ActiveFolder, Inbox As String)
Dim myNamespace As Outlook.NameSpace
Dim myFolder As Outlook.Folder
Dim Subfolder As Outlook.Folder
Dim Item As Object
Dim myMtg As Outlook.MeetingItem
Dim objMsg As MailItem
Set objMsg = Application.CreateItem(olMailItem)
Set myNamespace = Application.GetNamespace("MAPI")
Set myFolder = myNamespace.Folders(ActiveFolder)
Set Folders = myFolder.Folders
Set Subfolder = Folders.Item(Inbox)
For Each Item In Subfolder.Items
If Item.MessageClass = "IPM.Schedule.Meeting.Request" Then
'Convert Appointment to Email and Forward message
'Its Sudo-code and not working
objMsg.To = "example#emp.com"
objMsg.Subject = Item.Subject
objMsg.Body = Item.Body
objMsg.Send
End If
Next
End Sub
It is important to copy body text from Appointment as well as Subject and send to another email address.
I cannot forward this appointment. I have to convert it to email.
UPDATE
I added one line of code and it works:
Set myMtg = Item
objMsg.To = "example#emp.com"
objMsg.Subject = myMtg.Subject
objMsg.Body = myMtg.Body
objMsg.Send

If you want to send an existing meeting item as a regular email you need to set the MessageClass property to IPM.Notefirst. The MessageClass property links the item to the form on which it is based. When an item is selected, Outlook uses the message class to locate the form and expose its properties, such as Reply commands. Then you can cast the object to the MailItem class and call the Send method (of course, after specifying recipients).
At the opposite side, the Forward method of the MeetingItem class executes the Forward action for an item and returns the resulting copy as a MeetingItem object. So, basically a new MeetingItem object that represents the new meeting item is returned which can be sent.

Related

Reply All with Body of Top Email in Inbox

I'm attempting to create a VBA script to reply all to the most recent (top) email in my inbox.
I'm using the following code and am very close, but it need to it to default to the top email in my inbox rather that the one currently selected:
Sub my_test(Item As Outlook.MailItem)
Dim objItem As Object
Dim mail As MailItem
Dim replyall As MailItem
Dim templateItem As MailItem
For Each objItem In ActiveExplorer.Selection
If objItem.Class = olMail Then
Set mail = objItem
Set replyall = mail.replyall
Set templateItem = CreateItemFromTemplate("Template")
With replyall
.HTMLBody = templateItem.HTMLBody & .HTMLBody
.Display
End With
End If
Next
End Sub
but it need to it to default to the top email in my inbox rather that the one currently selected
The top email depends on the sorting order used for the view or folder in Outlook. Typically items are sorted by the RecievedTime property which returns a date indicating the date and time at which the item was received. So, you can sort the Items collection using the Sort method and get the first or last one which will be the top item in the view.
Sub SortByRecievedDate()
Dim myNameSpace As Outlook.NameSpace
Dim myFolder As Outlook.Folder
Dim myItem As Object
Dim myItems As Outlook.Items
Set myNameSpace = Application.GetNamespace("MAPI")
Set myFolder = myNameSpace.GetDefaultFolder(olFolderTasks)
Set myItems = myFolder.Items
myItems.Sort "[RecievedTime]", False
For Each myItem In myItems
MsgBox myItem.Subject & "-- " & myItem.DueDate
Next myItem
End Sub
But ideally you need to get the sorting order from the View object in Outlook. The View object allows you to create customizable views that allow you to better sort, group and ultimately view data of all different types. There are a variety of different view types that provide the flexibility needed to create and maintain your important data. You can be interested in the View.Filter property which returns or sets a string value that represents the filter for a view. The XML definition describes the view type by using a series of tags and keywords corresponding to various properties of the view itself. When the view is created, the XML definition is parsed to render the settings for the new view.

How to forward a calendar item without notifying organizer

I want to forward all calendar items within a certain date range to a specific email address without notifying the organizer.
Is there a way to do this using VBA code? I have the below code to not notify the meeting organizer but need to modify to forward all calendar items to a specific email address?
Also note I cannot forward as icalendar. I have a script which forwards emails when moved to a specific folder, however i cannot seem to convert or move meeting invites into the normal inbox folder.
Sub ForwardMeetingInvitation()
Dim olSel As Selection
Dim olMeeting As MeetingItem
Dim olFWMeeting As MeetingItem
Dim Recip As String
Set olSel = Outlook.Application.ActiveExplorer.Selection
Set olMeeting = olSel.Item(1)
'Replace with your own desired recipient's email address
Recip = "pirate#fakemail.com"
Set olFWMeeting = olMeeting.Forward
With olFWMeeting
.Recipients.Add (Recip)
.Attachments.Add olMeeting
.Display
End With
Set olSel = Nothing
Set olMeeting = Nothing
Set olFWMeeting = Nothing
End Sub

Send an email and ReplyAll to it

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

search for emails with specific subject title IF UNREAD and save attachments into folder

I am using the following vba code which should search for all emails with a specific subject title i.e. with the subject 'test'
Then only if the email is unread then save the attachment from that email into a folder.
There may be one or several emails with the subject test so I want all the unread emails with the subject test to have their attachments saved to the folder.
Here is my code:
Sub Work_with_Outlook()
Set olApp = CreateObject("Outlook.Application")
Dim olNs As Outlook.Namespace
Dim Fldr As Outlook.MAPIFolder
Dim myItem As Object
Dim myAttachment As Outlook.Attachment
Dim I As Long
Dim olMail As Variant
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderInbox)
Set myTasks = Fldr.Items
Set UnRead = myTasks.Restrict("[UnRead] = False")
Set olMail = myTasks.Find("[Subject] = ""test""")
If Not (olMail Is Nothing) And UnRead.Count = 0 Then
For Each myItem In myTasks
If myItem.Attachments.Count <> 0 Then
For Each myAttachment In myItem.Attachments
If InStr(myAttachment.DisplayName, ".txt") Then
I = I + 1
myAttachment.SaveAsFile "\\uksh000-file06\Purchasing\NS\Unactioned\" & myAttachment
End If
Next
End If
Next
For Each myItem In myTasks
myItem.UnRead = False
Next
MsgBox "Scan Complete."
Else
MsgBox "There Are No New Supplier Requests."
End If
End Sub
This does work to some degree, if I only have one email with the subject 'test' and it is unread then the script will get the attachment from that email and save it to my folder. However, if I have one email with the subject 'test' which is read and another email with the subject 'test' which is unread then the code won't work?
Please can someone show me where I am going wrong? Thanks in advance
It looks like you need to combine both comditions into a single one and use the Find/FindNext or Restrict methods to get an instance of the Items class which contains all items correspodning to your conditons. For example:
Set resultItems = myTasks.Restrict("[UnRead] = False AND [Subject] = ""test""")
See Enumerating, Searching, and Filtering Items in a Folder for information in MSDN.
Also you may find the sample code in the following articles:
How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)
How To: Use Restrict method to retrieve Outlook mail items from a folder
How To: Get unread Outlook e-mail items from the Inbox folder
Advanced search in Outlook programmatically: C#, VB.NET

Auto Reply with notes, email body and add CC

I am try to CC second person but I am getting Error run-time 13 Type mismatch.
Option Explicit
'// Auto Replay with notes and email body- run Action Script
Public Sub ReplywithNote(Item As Outlook.MailItem)
Dim olInspector As Outlook.Inspector
Dim olDocument As Word.Document
Dim olSelection As Word.Selection
Dim olReply As MailItem
Dim olRecipient As Outlook.Recipient
Set olReply = Item.ReplyAll
olReply.Display
Set olRecipient = myItem.Recipient.Add("omar")
olRecipient.Type = olCC
Set olInspector = Application.ActiveInspector()
Set olDocument = olInspector.WordEditor
Set olSelection = olDocument.Application.Selection
olSelection.InsertBefore "Received, Thank you."
'// Uncomment to send
olReply.Send
End Sub
Thanks.
Try Recipient not Recipients
Dim olRecipient As Outlook.Recipient
The Add method of the Recipients class creates a new recipient in the Recipients collection. The parameter is 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.
If you run the following sample code in Outlook there is no need to create a new Application instance, use the Application property available in VBA out of the box.
Set myOlApp = CreateObject("Outlook.Application") // Application
Set myItem = myOlApp.CreateItem(olMailItem)
Set myRecipient = myItem.Recipients.Add ("Jon Grande")
myRecipient.Type = olCC
Don't forget to call the Resolve method of the Recipient class after adding a new one. Or just the ResolveAll method of the Recipients class to resolve recipients against the address book.
See How to: Specify Different Recipient Types for a Mail Item for more information.