Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete text with Replace

I would like to remove a corporate sentence at the beginning of each incoming external email.

THINK SECURE. This email has come from an external source. Do not click on links or open attachments unless you recognise the sender.

It is highlighted in yellow.

Thanks to the assistance of this community, the below code works, but all subsequent unrelated Internet content of emails are also removed, leaving only the raw hyperlinks (no more banner, pictures..). I would like to remove only the sentence shown above.

I have tried all combinations body/htmlbody/RTFbody.

Sub RemoveExpressionFOLDER()

Dim outNS As Outlook.NameSpace
Dim outFldr As Outlook.Folder
Dim outMailItems As Outlook.Items
'Dim outMailItem As Outlook.MailItem
Dim outMailItem As Object
'Dim myinspector As Outlook.Inspector

Set outNS = Application.GetNamespace("MAPI")
Set outFldr = Application.ActiveExplorer.CurrentFolder

'Set myinspector = Application.ActiveInspector

Set outMailItems = outFldr.Items

K = outFldr.Items.Count

For i = K - 10 To K

    If outMailItems(i).Class <> olMail Then GoTo 20

    outMailItems(i).Display

    'outMailItems(i).UnRead = True
    outMailItems(i).Body = Replace(outMailItems(i).Body, "THINK SECURE. This email has come from an external source. Do not click on links or open attachments unless you recognise the sender.", "")
    'outMailItems(i).HTMLBody = Replace(outMailItems(i).HTMLBody, "THINK SECURE. This email has come from an external source. Do not click on links or open attachments unless you recognise the sender.", "")
    ' outMailItems(i).BodyFormat = olFormatHTML

    outMailItems(i).Save
    'Set myinspector = Application.ActiveInspector
    'Set outMailItems(i) = myinspector.CurrentItem

    outMailItems(i).Close olSave

20    Next i
MsgBox ("cleaned ")

Set outMailItems = Nothing
Set outFldr = Nothing
Set outNS = Nothing

End Sub
like image 656
Christian Fischer Avatar asked Apr 27 '26 18:04

Christian Fischer


1 Answers

I think you had the right idea of changing the HTMLBody instead of the Body. However with that, you ran into two issues:

a. you couldn`t save with .Save and hat to use .Close olSave

b. With the method .Display, Outlook already modifies the E-Mail and removes most of its HTML/CSS since Outlook may not know all HTML tags and CSS selectors. You will see this effect especially with responsive E-Mails.

The following should do the trick:

Sub RemoveExpressionFOLDER()
For Each mail In Application.ActiveExplorer.CurrentFolder.Items
    With mail
        If .Class <> olMail Then continue
        .UnRead = True
        .HTMLBody = Replace(.HTMLBody, "THINK SECURE. This email has come from an external source. Do not click on links or open attachments unless you recognise the sender.", "")
        .Close olSave
    End With
continue:
Next mail
MsgBox ("cleaned ")
End Sub
like image 114
miwin Avatar answered Apr 30 '26 09:04

miwin