An Outlook user wanted to know how to get part of a field and insert it into the message body. This is actually easy to do.
How do I get the domain name from an email address and add it to the message body? I have an email list of clients in Outlook and I would like to send them email. In the body part of mail, I would like to add their website domain. For example, I need to send mail to bob@domain.com and want to insert "Reference: domain.com".
You just need to find the position where the delimiting characters (in this case, the @ sign) is and get the letters going forward or backward.
The good news: It's less complicated than it sounds. Once you get that, you can insert it into a message body using Item.Body = "Reference: " & string . See Send message to contact for an example.
You can also use RegEx to find strings. See Use RegEx to parse message text
You can use this for more than just parsing an email address. If you receive email containing clearly identified fields ("Email: me@domain.com First Name: Mary Last Name: Smith") you can use this method to save the data.
To do this you need to use the VBA functions Len, Right, Left, Mid, and InStr.
Len
Len gets the length of a string, beginning at a starting point.
If you use test = Len("diane"), test will return 5.
Left or Right
Left or right will get the left-most or right-most characters.
string = Left ("phrase", get this many characters)
string = right ("phrase", get this many characters)
In test = Left ("diane", 3), test will equal "dia", the first 3 letters. Right("diane", 3) would give us "ane".
Mid
Mid gets words from the middle of a phrase. You need to enter both the starting point and how many characters.
string = Mid("phrase", start at, get this many characters)
If we use test = Mid("diane", 2, 3), it starts at the second characters and gets the next 3, for "ian".
InStr
InStr gets the position of a character within a string.
integer = InStr(start at, "phrase", "character or string")
So, test = InStr(1, "diane", "i") tells us the position of the i in diane is 2. The 1 tells it to start at the beginning of the string or phrase.
If we know the character we want is in the string twice, we can tell it to start looking later:
test = InStr(4, "slipstick", "i") tells me that there is an i in position 7.
We can look for the starting position of multi-character strings too: test = InStr(1, "slipstick", "ic") returns a 7.
To use InStr in a macro, such as to look for one category when multiple categories are assigned to an item, you'd use this format:
If InStr(Item.Categories, "my category") Then
Match upper or lower case
You can ignore upper letters in a string by using the LCASE function: LCASE(String)
LCase(Item.Body) converts the message body to all lower case. This allows the code to work even if someone uses mixed case or all caps.
For example, this sample looks for the word "something" as the first word in the message body. Because it uses LCASE, it will match Something, something, SOmething, or SOMETHING.
If Left(LCase(Item.Body), 9) = "something" Then
'do something
End If
Combine the functions
By putting these functions together we can split Outlook fields apart, trim the length of fields, or look for specific characters in a field.
Below are some very basic examples of how to use these functions. Generally speaking, you want to get each variable separately to use in the Left, Right, or Mid functions as it makes it easier to read and find mistakes.
For example, this line works, but is harder to read and understand. This code gets the right most characters of the selected contacts email address, up to the position of the @ sign (i.e., the domain name):
strDomain = Right(oContact.Email1Address, Len(oContact.Email1Address) - InStr(1, oContact.Email1Address, "@"))
This code does the same as the version above but is easier to follow.
Get position of the @ sign
intATsign = InStr(1, oContact.Email1Address, "@")
Get the length of the address, minus the position of the @ sign
intAddress = Len(oContact.Email1Address) - intATsign
Get the right most characters from the phrase
strDomain = Right(oContact.Email1Address, intAddress)
This code shows how to use the Mid function to start counting from the position of a character and get the next xx characters.
intATsign = InStr(1, oContact.Email1Address, "@")
intAddress = Len(oContact.Email1Address) - intATsign
strDomain = Mid(oContact.Email1Address, intATsign + 1, intAddress)
Trim
Although not one of the functions you'll use to find and parse data, the Trim function can be useful to remove non-printing and leading or ending spaces from text.
string = Trim(string)
More Information
Print Outlook email attachments as they arrive
Add a Category to Contacts in a Contact Group (DL)
Saving All Messages to the Hard Drive Using VBA
Check for missing attachments before sending an Outlook email message
Adding Birthdays and Anniversaries to Outlook's Calendar
Removing Birthdays and Anniversaries from the Calendar
Disable Outlook 2010's No Subject Warning using VBA
Find the Distribution Lists a Contact Belongs to
Remove Cancelled Meeting Requests from Resource Calendar
Assign a keyword to a message field for tracking
Hi Diane, is there a wildcard option for the InStr formula? I'd like to find a string that starts with a "D", then some character, then a "-", so both strings like "DB-" and "D4-" get found.
Many thanks!
Ingo
No, instr does not use wildcards - but regex will work.
One of my regex examples is here - Use RegEx to extract text from an Outlook email message (slipstick.com)
Diane, I am looking to build an email forward event from words in an email. can you help with this, what would you charge?
It depends on exactly what you want to do and if I have a macro published that works as a base with only customizations needed. Generally, $100 - 200 to tweak an existing macro, but could be lower if the tweaks are simple. (And higher if I need to work from scratch.)
So basically I want to take an email that in the body of the email it says CompanyName: @companyname.com I want to grab, then have it forward the email to the BACK@companyname.com
That is basically this - Run a script rule: Autoreply using a template (slipstick.com)
or this one
Run a Script Rule: Forwarding Messages (slipstick.com)
Hi Diane,
Can you help me with similar case?
I'm receiving multiple email from automated server with the same subject, but the email body contain a different item#. I need a script to run (I'll set a rule to run the script for new emails from the specific sender) that will find the item# (digits) within the email body, edit the subject and change it to item# and save.
here is an example :
1. Email received:
From: example@domain.com
Subject: New email
This item# is for you. bla bla bla.
2. Run rule:
a. from : example@domain.com & Subject: New email
b. Run script :
i. find : item#
ii. Set email subject to: item#
iii. Save email.
3. Result:
From: Example@domain.com
Subject: item#
This item# is for you. bla bla bla.
You'll want to use regex to get the values from the body.
https://www.slipstick.com/developer/regex-parse-message-text/
myReply.HTMLBody = " Hello" & Mid$(Item.SenderName, InStr(1, Item.SenderName, " ")) & ", " & vbCrLf & myReply.HTMLBody
Hello,
The above line of code has been assisting me return the name of an email recipient to an email body. The problem I am having is this current line of code returns the First Name "Space" Middle Initial.
From the email name format Schneider, Brent T I am getting Brent T
I would like to only receive the first name so it reads as Hello Brent, instead of Hello Brent T, in the email body.
I believe with addition combination of the functions Mid$, Right$, Len, InStr, InStrRev in the line I would be able to get what I want but I am at a loss.
Any assistance would be greatly appreciated,
Brent Schneider
i would get the brent t into a variable, then split it at the space, using either instr as you are now or using the split function. Or you could try using instrrev to split the full name at the last space - but if you only want the first name, you'll still need to process it twice (i think).
How do I get the e-mail ID, contact number from an message body and add it to the to address? we receive the client mail ID through mail body form the search engine companies. I would like to send the client an automatic email using templates. In the body part of mail, I would like to extract the product they are seeking and I will insert it in to the subject field. For example, I need get the mail ID as bob@domain.com I want to copy this and use in to address. I want to copy the product "wireless" and put it in the subject. Please help
Use regex to grab the address and assign it to a variable then you can assign it to the To field. See https://www.slipstick.com/developer/regex-parse-message-text/ for samples.
Here is the code: Sub Country() Dim olApp As Outlook.Application Dim olNS As Outlook.NameSpace Dim olFolder As Outlook.MAPIFolder Dim Item As MailItem Dim regEx As Object Dim olMatches As Object Dim strBody As String Dim bcount As String Dim badAddresses As Variant Dim i As Long Dim xlApp As Object 'Excel.Application Dim xlwkbk As Object 'Excel.Workbook Dim xlwksht As Object 'Excel.Worksheet Dim xlRng As Object 'Excel.Range Set olApp = Outlook.Application Set olNS = olApp.GetNamespace("MAPI") Set olFolder = olNS.Folders("mail.com").Folders("Inbox").Folders("New Emails") Set regEx = CreateObject("VBScript.RegExp") 'define regular expression regEx.Pattern = "(Reply to What Country are you from\?:\s*([A-Za-z ]*\r))" regEx.IgnoreCase = True regEx.MultiLine = True ' set up size of variant bcount = olFolder.Items.count ReDim badAddresses(1 To bcount) As String ' initialize variant position counter i = 0 ' parse each message in the folder holding the bounced emails For Each Item In olFolder.Items i = i + 1 strBody = olFolder.Items(i).Body Set olMatches = regEx.Execute(strBody) If olMatches.count >= 1 Then badAddresses(i) = olMatches(0) Item.UnRead = False End If Next Item ' write everything to Excel Set xlApp = GetExcelApp If xlApp Is Nothing Then GoTo ExitProc If Not IsFileOpen("\Desktop\email.xlsx") Then Set xlwkbk = xlApp.Workbooks.Open(Environ("USERPROFILE") & "\Desktop\email.xlsx") End If Set xlwksht = xlwkbk.Sheets(1)… Read more »
Diane,
Thanks, but I tried both of your recommendations and I get a run time error when I changed olmatches(1). Also, I tried to wrap the pattern as well and it still comes back with "What Country are you from\?: India". Not sure why it still pulls the preceding text before the match code.
Can you post the full code you are using to get India? The number inside the match() counts the number of parentheses - starting with 0 (for one pair) so match(0) should get just India when the only parens around the regex for India. If it's match(1), and you use () around the entire pattern then should get the second set, which is around the regex for India.
Thanks! I had to change up a little to get it to work, but this code below works now:
"Reply to What Country are you from\?:\s*([A-Za-z ]*\r)"
Is there a way to only retrieve everything after Reply to What Country are you from\?:
This code pulls Reply to What Country are you from\?: India. This works, but I have to cleanup in Excel, so just curious as to how I could retrieve only "India".
I appreciate your help!!!
With that pattern, it should only get what is in the () in the match code: olmatches(0). Try olmatches(1) and wrap the pattern in (): "(Reply to What Country are you from\?:\s*([A-Za-z ]*\r))".