Question

Good morning all,

I am hoping someone can help me here with a piece of coding.

I am looking to save the selected email to a specific directory, with the name of the email, and of course as a .msg file. This is what i have today, and it is not working. It saves a file but the name only has the first 2 characters (looks like it errors after the semi colon file name eg: FW or RE)... the content of the file is blank and the filetype has not been applied.

'code to save selected email
Dim selectedEmail As MailItem
Set selectedEmail = ActiveExplorer.Selection.Item(1)
Dim emailsub As String
emailsub = ActiveExplorer.Selection.Item(1).Subject
    With selectedEmail
        .SaveAs "C:\direcotry\folder\" & emailsub & ".msg", olMSG
    End With

Thank you in anticipation. Dom

Was it helpful?

Solution

The reason is very simple. You email subject contains and Invalid Character. For example : This usually happens when the email is a RE: or FWD:

Try this

Sub Sample()
    Dim selectedEmail As MailItem
    Dim emailsub As String

    Set selectedEmail = ActiveExplorer.Selection.Item(1)

    emailsub = GetValidName(selectedEmail.subject)

    'Debug.Print emailsub

    With selectedEmail
        .SaveAs "C:\direcotry\folder\" & emailsub & ".msg", OlSaveAsType.olMSG
    End With
End Sub

Function GetValidName(sSub As String) As String
    '~~> File Name cannot have these \ / : * ? " < > |
    Dim sTemp As String

    sTemp = sSub

    sTemp = Replace(sTemp, "\", "")
    sTemp = Replace(sTemp, "/", "")
    sTemp = Replace(sTemp, ":", "")
    sTemp = Replace(sTemp, "*", "")
    sTemp = Replace(sTemp, """", "")
    sTemp = Replace(sTemp, "<", "")
    sTemp = Replace(sTemp, ">", "")
    sTemp = Replace(sTemp, "|", "")

    GetValidName = sTemp
End Function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top