MailItems are one of the more commonly automated items in the Outlook VBA object model. Here's how we can create them using several different methods.
Follow the links above to learn more about the MailItem's methods, properties and events.
Create MailItem in default local folder
MailItems can be created in the default Inbox folder using the Outlook.CreateItem Method.
Function CreateMailitem() As Outlook.AppointmentItem Set CreateMailitem = Outlook.CreateItem(olMailItem) End Function
Create Mailitem in non-default local folder that holds mail items
MailItems may be created in any folder that can hold them. Pass a MAPIFolder Object to this function and it uses the Folder.Items.Add Method to create a new message and pass it back to the calling procedure for further manipulation.
Function CreateMailItemAltFolder(fldr As Outlook.MAPIFolder) As Outlook.MailItem If fldr.DefaultItemType = olMailItem Then Set CreateMailItemAltFolder = fldr.Items.Add(olMailItem) End If End Function
Create MailItem in shared default folder
You may create MailItems in a shared folder to which you have access. You pass in either a resolved Recipient object or the name of a user whose shared Inbox folder you have access to and want to create a message for.
Function CreateSharedDefaultMailItem(recip As Variant) As Outlook.MailItem Dim olNS As Outlook.NameSpace Dim fldr As Outlook.MAPIFolder Dim tempRecip As Outlook.recipient Select Case TypeName(recip) Case "Recipient" ' Recipient object already created Set fldr = olNS.GetSharedDefaultFolder(recip, olFolderInbox) Case "String" ' create Recipient object Set olNS = GetNS(GetOutlookApp) Set tempRecip = olNS.CreateRecipient(recip) Set fldr = olNS.GetSharedDefaultFolder(tempRecip, olFolderInbox) End Select Set CreateSharedDefaultMailItem = fldr.Items.Add(olMailItem) End Function Function GetNS(ByRef app As Outlook.Application) As Outlook.NameSpace Set GetNS = app.GetNamespace("MAPI") End Function Function GetOutlookApp() As Outlook.Application ' returns reference to native Application object Set GetOutlookApp = Outlook.Application End Function
If a Recipient object is passed to the function, the new MailItem is created directly. If only a name is passed, a temporary Recipient object is created using the Outlook.NameSpace.CreateRecipient Method.