Question

So I want to edit my received mails afterwards to add links. If the emails have been received as plain text or HTML I have just edited the appropriate msg.Body or msg.HTMLBody. However, for Rich Text, editing RTFBody directly seems both rather complicated and keeps crashing my Outlook.

I can edit the HTMLBody of Rich Text mails, but it then converts the whole mail to HTML which makes it change appearance and can't handle embedded attachments well.

MSDN talks about MailItem.GetInspector, which returns WordEditor and allows a much easier way of editing documents. Problem is, all examples I've found are of new mails being created, not existing being edited. The following code:

        Set objInsp = itm.GetInspector
        Set objDoc = objInsp.WordEditor
        objDoc.Characters(1).InsertBefore "string"

Generates the following error: Run-time error '4605', This method or property is not available because the document is locked for editing.

Does anyone know a way to unlock the mailitem to allow for editing, alternatively, a way to edit RTFBody that doesn't go belly up? I've tried to set the objDoc.ProtectionType to something that allows writing, but it also says I cannot change the document.

Was it helpful?

Solution

I was facing exactly the same issue (Outlook VBA: Replace inline object with text). As posted in my comment (soon to be edited to a more polished version, after further testing), you have to use objDoc.UnProtect prior to modifying contents. I have actually used

'On Error Resume Next   ' This will prevent the error message... risky!
Dim odProt As Integer
odProt = objDoc.ProtectionType
If (odProt <> wdNoProtection) Then
    Debug.Print "Document is protected with type " & odProt & ", unprotecting temporarily"
    objDoc.UnProtect
End If
' ... Write your code
If (odProt <> wdNoProtection) Then
    Debug.Print "Restoring protection"
    objDoc.Protect (odProt)
End If
objMsg.Display
objMsg.Save

I am not sure if the last two lines are the best, but it worked for me.

Note that having On Error Resume Next will prevent the error message, and you may see that none of your editions has any effect without apparent reason.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top