How to get specific name of email recipient in mail
To get the specific name of an email recipient in a mail, you can use the To
property of the MailItem
object in Outlook VBA. Here's an example:
Sub GetRecipientName()
Dim olApp As New Outlook.Application
Dim olMail As MailItem
Set olMail = olApp.CreateItem(0) ' 0 = MailItem
' Set the recipient's email address
olMail.To = "[email protected]"
' Get the recipient's name
Dim recipientName As String
recipientName = olMail.Recipients(1).Name
' Display the recipient's name
MsgBox recipientName
End Sub
In this example, we create a new MailItem
object and set the To
property to the email address of the recipient. We then use the Recipients
collection to access the recipient's name, and store it in the recipientName
variable. Finally, we display the recipient's name using a MsgBox
.
Note that the Recipients
collection is a collection of Recipient
objects, and each Recipient
object has a Name
property that contains the recipient's name. In this example, we access the first recipient in the collection using olMail.Recipients(1)
, but you can loop through the collection to access multiple recipients.
Alternatively, you can use the GetRecipient
method to get a specific recipient by their email address:
Sub GetRecipientName()
Dim olApp As New Outlook.Application
Dim olMail As MailItem
Set olMail = olApp.CreateItem(0) ' 0 = MailItem
' Set the recipient's email address
Dim recipientEmail As String
recipientEmail = "[email protected]"
' Get the recipient's name
Dim recipient As Recipient
Set recipient = olMail.GetRecipient(recipientEmail)
If recipient IsNot Nothing Then
Dim recipientName As String
recipientName = recipient.Name
' Display the recipient's name
MsgBox recipientName
Else
MsgBox "Recipient not found"
End If
End Sub
This code uses the GetRecipient
method to get a Recipient
object for the specified email address. If the recipient is found, we access their name using the Name
property and display it using a MsgBox
. If the recipient is not found, we display an error message.