Outlook 2010 VBA code to show alias of recipient - vba

My company assigns each employee an ID which is stored as their 'alias' in Outlook. We use this ID often, and I am looking for an easy way to see it.
Right now I enter the recipient name in a new email, double click the name, click on more options, then Outlook properties. I am looking for a macro that where I would enter the recipient name in a new email, and then run the macro which would just pop up the recipient's alias as a message box (ideally copy it to the clipboard). I have tried (and failed) to write this on my own.
The code I have so far is below. However, this code gives /o=corpexchange/ou=exchange administrative group.....
I am trying to get it to return the alias
Sub ReadRecpDetail2()
Dim myOlApp As Outlook.Application
Dim myItem As Outlook.MailItem
Dim myRecipient As Outlook.recipient
Dim recipient As Outlook.recipient
Set myOlApp = GetObject(, "Outlook.Application")
Set myItem = myOlApp.ActiveInspector.CurrentItem
For Each recipient In myItem.Recipients
recipient.Resolve
MsgBox recipient.AddressEntry
Next recipient
End Sub
To Recreate:
Open new outlook email
Enter email address and resolve
Run macro

Try to use the following methods:
Use the CreateRecipient method of the Namespace class to create a Recipient object.
Call the Resolve method of the Recipient class to resolve a Recipient object against the Address Book.
Get the AddressEntry property value, returns the AddressEntry object corresponding to the resolved recipient.
Call the GetExchangeUser method of the AddressEntry class, it returns an ExchangeUser object that represents the AddressEntry if the AddressEntry belongs to an Exchange AddressList object such as the Global Address List (GAL) and corresponds to an Exchange user.
The Alias property of the ExchangeUser class returns a String representing the alias for the ExchangeUser.
You may also find the Getting Started with VBA in Outlook 2010 article helpful.

With all your help I was able to solve this by capturing recipient address entry, adding it as a new item, showing alias, then deleting the recipient:
Sub ReadRecpDetail()
Dim myOlApp As Outlook.Application
Dim myItem As Outlook.mailItem
Dim myRecipient As Outlook.recipient
Dim recipient As Outlook.recipient
Dim SMTPaddress As String
Dim entry As Outlook.AddressEntry
Dim entrystring As String
Dim Copytoclipboard As New DataObject
Set myOlApp = GetObject(, "Outlook.Application")
Set myItem = myOlApp.ActiveInspector.CurrentItem
Set recipient = myItem.Recipients.Item(1)
Set myRecipient = myItem.Recipients.Add(recipient.AddressEntry)
myRecipient.Resolve
entrystring = myRecipient.AddressEntry.GetExchangeUser.Alias
MsgBox (entrystring)
Copytoclipboard.SetText entrystring
Copytoclipboard.PutInClipboard
myRecipient.Delete
End Sub

I had a similar situation where I needed to print out all the user names of the recipients in an email so I could export them to another application. I based my solution off of your answer which is below in case it helps anyone else.
Sub PrintRecipientAliases()
Dim myOlApp As Outlook.Application
Dim myItem As Outlook.MailItem
Dim recipient As Outlook.recipient
Set myOlApp = GetObject(, "Outlook.Application")
Set myItem = myOlApp.ActiveInspector.CurrentItem
For Each recipient In myItem.Recipients
With recipient
Debug.Print recipient.AddressEntry.GetExchangeUser.Alias
End With
Next
End Sub

Related

Get the list of all possible email addresses starting from Display Name

How could I get, with VBA Excel, the Outlook properties of a single contact for whom I have the User Principal Name?
I am interested in the tab labelled "E-mail Addresses".
I managed to get the PrimarySMTP property, but I would like to get the list of all addresses listed there. The 'alias' property gives me one entry, while there are several others.
This is what I did to get the distribution list memberships:
Dim objExchUsr As ExchangeUser
Dim myolApp As Outlook.Application
Dim myNameSpace As Namespace
Dim MyAddrList As AddressList
Dim myRecipient As Outlook.Recipient
Dim oDistListEntries As Outlook.AddressEntries
Dim oAE As Outlook.AddressEntry
Set myolApp = CreateObject("Outlook.Application")
Set myNameSpace = myolApp.GetNamespace("MAPI")
Set MyAddrList = myNameSpace.addressLists("Global Address List")
Set myRecipient = myNameSpace.CreateRecipient(strDisplayname)
myRecipient.Resolve
If myRecipient.Resolved Then
Set objExchUsr = myRecipient.AddressEntry.GetExchangeUser
Set oDistListEntries = objExchUsr.GetMemberOfList
For Each oAE In oDistListEntries
If oAE.AddressEntryUserType = olExchangeDistributionListAddressEntry Then
<Do something with the distribution lists: not relevant to this problem>
End If
Next
End If
With this code I get the information shown in the tab 'Member Of' of the Outlook Properties.
How do I get the information that is shown in the tab 'E-mail Addresses'?
Here is the code you could use:
Const PR_EMS_AB_PROXY_ADDRESSES As String = _
"http://schemas.microsoft.com/mapi/proptag/0x800F101F"
Dim NS As Outlook.NameSpace
Set NS = Application.GetNamespace("MAPI")
addresses = _
NS.CurrentUser.AddressEntry.PropertyAccessor.GetProperty(PR_EMS_AB_PROXY_ADDRESSES)
You need to read the PR_EMS_AB_PROXY_ADDRESSES MAPI property (DASL name "http://schemas.microsoft.com/mapi/proptag/0x800F101F") using AddressEntry.PropertyAccessor.GetProperty. You will get back an array of proxy addresses prefixed with the address type (e.g. "EX:" or "SMTP:")

Is there any way to get the Distribution Group name of a NewEmail Event in Outlook VBA?

I'm trying to divert new emails in Outlook from a distribution group called Customer Service to a subfolder during a certain time. I don't think rules have the capability to divert emails at a certain time so I'm using Application.NewEmail Event.
I have my code set up right now so that it could divert emails from an Exchange sender's email address to a subfolder. However, I need to somehow be able to do the same thing with a Distribution Group and I'm not sure how to extract the information necessary to identify a distribution group.
Here's my code:
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 cusItem As Object)
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
Dim strAddress As String, strEntryId As String
Dim objAddressentry As Outlook.AddressEntry, objExchangeUser As Outlook.ExchangeUser
Dim objReply As Outlook.MailItem, objRecipient As Outlook.Recipient
Dim objDestFolder As Outlook.MAPIFolder
If TypeName(cusItem) = "MailItem" And cusItem.SenderEmailType = "EX" Then
On Error GoTo ErrorHandler
Set objReply = cusItem.Reply()
Set objRecipient = objReply.Recipients.Item(1)
strEntryId = objRecipient.EntryID
objReply.Close OlInspectorClose.olDiscard
Set objAddressentry = objNS.GetAddressEntryFromID(strEntryId)
Set objExchangeUser = objAddressentry.GetExchangeUser()
strAddress = objExchangeUser.PrimarySmtpAddress()
If strAddress = "jabach#example.com" And TimeValue(Now()) >= TimeValue("08:00:00 AM") And TimeValue(Now()) <= TimeValue("05:00:00 PM") Then
Set objDestFolder = objNS.GetDefaultFolder(olFolderInbox).Folders("ryule")
cusItem.Move objDestFolder
End If
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description & vbCrLf & "Click Ok to continue"
Resume ProgramExit
End Sub
There's also some issues with Application_Startup() not actually firing up Outlook which is why I have all those variables declared twice.
You need to check out the AddressEntry.AddressEntryUserType property which returns a constant from the OlAddressEntryUserType enumeration representing the user type of the AddressEntry. AddressEntryUserType provides a level of granularity for user types that is finer than that of AddressEntry.DisplayType. The DisplayType property does not distinguish users with different types of AddressEntry, such as an AddressEntry that has a Simple Mail Transfer Protocol (SMTP) email address, a Lightweight Directory Access Protocol (LDAP) address, an Exchange user address, or an AddressEntry in the Outlook Contacts Address Book. All these entires have olUser as their AddressEntry.DisplayType. For example:
Sub DemoAE()
Dim colAL As Outlook.AddressLists
Dim oAL As Outlook.AddressList
Dim colAE As Outlook.AddressEntries
Dim oAE As Outlook.AddressEntry
Dim oExUser As Outlook.ExchangeUser
Set colAL = Application.Session.AddressLists
For Each oAL In colAL
'Address list is an Exchange Global Address List
If oAL.AddressListType = olExchangeGlobalAddressList Then
Set colAE = oAL.AddressEntries
For Each oAE In colAE
If oAE.AddressEntryUserType = _
olExchangeUserAddressEntry Then
Set oExUser = oAE.GetExchangeUser
Debug.Print(oExUser.JobTitle)
Debug.Print(oExUser.OfficeLocation)
Debug.Print(oExUser.BusinessTelephoneNumber)
End If
Next
End If
Next
End Sub
So, you may need to use the AddressEntry.GetExchangeDistributionList method in case of Exchange distribution lists.
The OlAddressEntryUserType enumeration provides the following constants:
olExchangeAgentAddressEntry - An address entry that is an Exchange agent.
olExchangeDistributionListAddressEntry - An address entry that is an Exchange distribution list.
olExchangeOrganizationAddressEntry - An address entry that is an Exchange organization.
olExchangePublicFolderAddressEntry - An address entry that is an Exchange public folder.
olExchangeRemoteUserAddressEntry - An Exchange user that belongs to a different Exchange forest.
olExchangeUserAddressEntry - An Exchange user that belongs to the same Exchange forest.
olLdapAddressEntry - An address entry that uses the Lightweight Directory Access Protocol (LDAP).
olOtherAddressEntry - A custom or some other type of address entry such as FAX.
olOutlookContactAddressEntry - An address entry in an Outlook Contacts folder.
olOutlookDistributionListAddressEntry - An address entry that is an Outlook distribution list.
olSmtpAddressEntry - An address entry that uses the Simple Mail Transfer Protocol (SMTP).
Finally, I'd suggest handling 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.

Query Outlook Global Address List From Access VBA

I am writing some Access VBA code to get a count of how many times a specific email address has been emailed. The issue that I am running into is that the first time the email is sent out, the email leaves our Exchange sever as
email1#domain.com
But once the person replies to that email, then all subsequent messages are displayed as
'lastname, firstname'
I use the below VBA code to search for the email1#domain.com example, but how can I use access vba to get the name from the global address list?
Function Test()
Dim searchEmail As String: searchEmail = "'abc123#abc123.com'"
Dim olApp As Outlook.Application
Dim olNs As NameSpace
Dim Fldr As MAPIFolder
Dim olReply As Outlook.MailItem
Dim msg As Object
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderSentMail)
For Each msg In Fldr.Items
If TypeName(msg) = "MailItem" Then
If msg.To = searchEmail Then
'now we start counting
End If
End If
Next msg
End Function
Similar to the answer I posted here, instead of checking the To property of the MailItem object (which, per the linked documentation, contains the display names only), query the contents of the Recipients collection and, for each Recipient object, test the value held by the Address property against your searchEmail variable.
The Address property will consistently contain the email address of the recipient, never a display name.
That is, instead of:
For Each msg In Fldr.Items
If TypeName(msg) = "MailItem" Then
If msg.To = searchEmail Then
'now we start counting
End If
End If
Next msg
You might use something like:
For Each msg In Fldr.Items
If TypeName(msg) = "MailItem" Then
For Each rcp In msg.Recipients
If rcp.Address = searchEmail Then
'now we start counting
End If
Next rcp
End If
Next msg

Convert Appointment to Email and send

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.

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.