Save Mails
In Outlook, sometimes you want to backup or save your emails to your local drive. What if amount of emails is in thousands? Ahh!!!!, No worries, in this PoC I will be giving an automated way to backup or save your outlook emails for a specific folder to your local drive.
Code example
Public Sub SaveOutlookMessage() Dim oPathToSave As String 'Where all messages will be saved oPathToSave = "C:\Users\Downloads\Blogs\msg\" Dim folderName As String 'Folder name in outlook from which all message will be retrived folderName = "Advertise" 'Outlook application object declaration Dim oApp As Outlook.Application 'bind current outlook instance Set oApp = GetObject("", "Outlook.Application") 'Get MAPI Folder Dim oNameSpace As Namespace Set oNameSpace = oApp.GetNamespace("MAPI") 'Get Advertise folder Dim oFolder As MAPIFolder Set oFolder = oNameSpace.Folders.Item(1).Folders(folderName) 'Iterate each item Dim oMailItem As MailItem For Each oMailItem In oFolder.Items 'Save item Dim oNameToSave As String 'Remove illegal chars oNameToSave = RemoveIllegalChar(oMailItem.Subject) 'Save mail oMailItem.SaveAs oPathToSave & oNameToSave & ".msg" Next oMailItem 'CleanUp If Not oMailItem Is Nothing Then Set oMailItem = Nothing End If If Not oFolder Is Nothing Then Set oFolder = Nothing End If If Not oNameSpace Is Nothing Then Set oNameSpace = Nothing End If If Not oApp Is Nothing Then Set oApp = Nothing End If End Sub
Supporting Function
Function RemoveIllegalChar(oInput As String) Dim RegX As Object Set RegX = CreateObject("vbscript.regexp") RegX.Pattern = "[\" & Chr(34) & "\!\@\#\$\%\^\&\*\(\)\=\+\|\[\]\{\}\`\'\;\:\<\>\?\/\,]" RegX.IgnoreCase = True RegX.Global = True RemoveIllegalChar = RegX.Replace(oInput, "") ExitFunction: If Err.Number <> 0 Then Set RegX = Nothing End If End Function
Input
In this example we will be reading “Advertise” folder which has couple of emails inside, which we will save in a local drive path. To format name we have taken mail subject as file name which we will be cleaning with a supported function as given above using RegEx.

Output

Next >> Get Selected Items in Outlook using VBA code example