Parse out information from a mail item to save Outlook message to external folder

49 Views Asked by At

I am trying to take a selected message in Outlook, parse out the date it was received, the sender, the recipients and the subject line, and then create a file name with those elements, and then save it to a specified folder as a .msg file.

How can I parse out the information from a mail item to get the elements into my variables?

Sub Save_Message()
    Set myOlApp = Outlook.Application
    Dim myOlExp As Outlook.Explorer
    Dim myOlSel As Outlook.Selection
    Dim mySender As Outlook.AddressEntry
    Dim oMail As MailItem
    
    Dim mSender As String
    Dim mRecipient As String
    Dim mDate As Date
    Dim mSubject As Long
    
    Set myOlExp = Application.ActiveExplorer
    Set myOlSel = myOlExp.Selection
    Set oMail = myOlSel.Item
    
    mSender = oMail.SenderName
    mRecipient = oMail.Recipients
    mDate = oMail.ReceivedTime
    mSubject = oMail.Subject
    
End Sub
2

There are 2 best solutions below

0
Dmitry Streblechenko On

Selection is a collection. If you want the first element, use

Set oMail = myOlSel.Item(1)

MailItem.Recipients returns Recipients collection, not a string. You can use To/CC/BCC properties (which are strings).

Make sure you remove characters invalid in file name (such as ":" and ";") when you construct the file name.

As a general rule, please include the errors you are seeing when running your code.

0
Eugene Astafiev On

The Selection object contains all selected items in an Outlook window. You need to iterate over all items in the collection or just get the first one:

Set myOlExp = Application.ActiveExplorer 
Set myOlSel = myOlExp.Selection 
For x = 1 To myOlSel.Count 
 If myOlSel.Item(x).Class = OlObjectClass.olMail Then 
   ' here you may call mail item properties and methods 
   Set oMail = myOlSel.Item(x) 
 End If

Be aware, the Selection collection may contain items of different types. It makes sense to check the item type before using any properties and methods in the code.

parse out the date it was received, the sender, the recipients and the subject line, and then create a file name with those elements in it, and then save it to a specified folder as a .msg file.

When you construct a file path or file name based on Outlook property values you need to make sure the result string doesn't contain forbidden symbols. See What characters are forbidden in Windows and Linux directory names? for more information.