With myMail
' This section cleans up the subject string and removes unwanted characters
'Two steps below assist in sorting emails by date, as well as use of hour/minute to provide uniqueness that subject header alone won't. This prevents overwriting of existing emails.
st_TempDate = Strings.Format(.ReceivedTime, "yyyy-MM-dd") 'Process date, use this as first part of filename
st_TempDate = st_TempDate & "_" & Strings.Format(.ReceivedTime, "HH-mm") 'Process time, use this as second part of filename, also remove colons as this breaks the file save.
'Next step filters subject line to remove unwanted characters from subject that may break filename conventions.
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = True
.Pattern = "[^a-zA-Z0-9 \r\t\n\f\-]" ' Maintain normal characters, remove any characters that may cause file save issues.
End With
st_TempSubject = regEx.Replace(.Subject, "")
st_FileTitle = fpath & "\" & st_TempDate & "_" & .Sender & "_" & st_TempSubject
lngCharacters = Len(st_FileTitle)
If lngCharacters > 255 Then ' hard coded Windows path length restriction, if this length is exceeded then save operation will fail.
msg_Title = "Path Length Error"
msg_Style = vbYesNo + vbQuestion + vbDefaultButton1
msg_Response = MsgBox("Path Length too long, path length is " & lngCharacters & ", do you want to decrease filename?", msg_Style, msg_Title, "Demo.hlp", 1000) ' User warning that mail has not been processed.
If msg_Response = vbYes Then
st_FileTitle = Left(st_FileTitle, 255) ' Path length restriction is 260, need to account for file extension in string...
Else
Set myMail = Nothing
Set fDialog = Nothing 'drop objects prior to exit
Set proxy = Nothing
Exit Sub
End If
End If
'this bit finally applies the .saveas method using the resultant strings to the path specified. Method appears incapable of providing success / fail return value.
.SaveAs st_FileTitle & ".msg", olMSG ' Method doesn't pass success / fail return value, code thus has risk of indicating mail has been saved when operation has failed.
.MarkAsTask (olMarkComplete) ' Use complete flag to indicate that mail has been filed - shows as completed but doesn't set tick...
.Close (olSave) ' turns out tick doesn't show up unless email is processed as closed.
End With
Set fDialog = Nothing ' Release objects on macro completion.
Set proxy = Nothing
Set myMail = Nothing