I want to edit my received mails to add links.
If the emails are plain text or HTML I edit the appropriate msg.Body
or msg.HTMLBody
.
For Rich Text, editing RTFBody directly seems complicated and crashes 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.
All examples I 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.
How do I unlock the mailitem to allow for editing?
Is there an alternatively way to edit RTFBody?
I tried to set the objDoc.ProtectionType to allow writing, but it also says I cannot change the document.
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.