Delete selected text from incoming emails

Not open for further replies.

Dr. Bartolo

Outlook version
Outlook 2016 32 bit
Email Account
My incoming e-mails are all marked with an additional line of text at the start. I have been trying to work out how to delete that text automatically (either by using a rule plus a script or in some other automatic way) and I cannot find anything to show me exactly what I want to do.

I think what I am after is a macro that runs on all incoming e-mails, searches for the text (in case it is not there!), deletes it if found (not forgetting to delete the carriage return at the end of the line), saves the result, and shows me the final version in my inbox.

If I could in addition choose to run that on all existing e-mails in one or more directories that would be a plus but is not essential.

Any ideas or (even better solutions!) would be greatly welcomed.
ItemAdd should work. It won't run on existing messages but you can use another macro to run on existing messages. once you get the code for new messages, the working part can be added to a macro that runs on selected messages or all messages in a folder. Base code here - Working with All Items in a Folder or Selected Items (Actually, it might be easier to test it with selected items macro then put the working part into the item .)

This is the base for an itemadd macro - How to use an ItemAdd Macro - replacing the text could be as simple as
replace(item.body, "the text" & vbcrlf, "")
Thank you for this, but having pored over it all for some time I am afraid I cannot make it work. I am much too much of a novice I suspect. Would it be possible for you to set out the full code here?
what happens when you try? Do you get any errors?

Did you set macro security to low and restart outlook? The application startup macro runs when outlook is restarted (but can be kick-started).
How to use Outlook's VBA Editor

Start with this macro from How to use an ItemAdd Macro - the copy and paste a message in place in the Inbox (Ctrl+C, V) - a message box should come up. Replace the msgbox line with this - 'the text' is the text you want to find (use the correct case). If that works add & vbcrlf to "the Text" - "the text" & vbcrlf - and do another copy paste. oh... you need to save the change - add

replace(item.body, "the text", "")

Option Explicit
Private objNS As Outlook.NameSpace
Private WithEvents objItems As Outlook.Items

Private Sub Application_Startup()
Dim objWatchFolder As Outlook.Folder
Set objNS = Application.GetNamespace("MAPI")

'Set the folder and items to watch:
Set objWatchFolder = objNS.GetDefaultFolder(olFolderInbox)
Set objItems = objWatchFolder.Items

Set objWatchFolder = Nothing
End Sub

Private Sub objItems_ItemAdd(ByVal Item As Object)

' Your code goes here
MsgBox "Message subject: " & Item.Subject & vbcrlf & "Message sender: " & Item.SenderName &" (" & Item.SenderEmailAddress & ")"


Set Item = Nothing
End Sub
BTW - if they are HTML messages, the results may not be what you are expecting.

You'll need to use one that uses the word editor and removes the first two lines. it would be based on the macro at Use Word Macro to Apply Formatting to Email - but would use different code in the With objSel / End With block.
When I pasted your code into the ThisOutlookSession and closed Outlook, on exiting I got a compile error: "Invalid attribute in Sub or Function" at the line "Private WithEvents objItems As Outlook.Items". Obviously the same thing happened when I restarted Outlook.

I think I should use the Word editor version anyway. What would the different code be that you refer to?
i haven't been able to get a word version working on incoming mail, only when composing (like if you are forwarding).

I'm not sure why you are getting errors on the code with a copy and paste - it works here error free. Are theire any leading spaces? I've noticed that copying from Edge can add invalid spaces at the beginning of the code (maybe the end too, but I've only noticed it at the beginning or in blank lines.)
I have managed to get rid of the original error (I am not quite sure how), and the message box did appear as you said it would. When I replaced it, however, I got a syntax error. No doubt I read your instructions wrongly. What I did was to replace the whole of

MsgBox "Message subject: " & Item.Subject & vbcrlf & "Message sender: " & Item.SenderName &" (" & Item.SenderEmailAddress & ")"


replace(item.body, "the text", "")

where "the text" is the phrase (in quotation marks) I want to get rid of, so if that is "Test text" it would read like this (with no leading spaces)

replace(item.body, "Test text", "")

I am probably missing something really simple, but I cannot see what.
I should have said the syntax error is on the replaced line of code.
ah... yeah, that is not complete.
you need to use
item.body = replace(item.body, "the text", "")
I am getting there! That works, and it also works if I add in & vbcrlf. The trouble is that I now see that there are three carriage returns I would like to get rid of. In my naivety I tried adding in two more & vbcrlf and, as I half suspected, that did less than nothing at all - in fact the code then did nothing!

My other problem is a bigger one. Almost all of my incoming e-mails are HTML. This code leaves those completely unaffected.
My other problem is a bigger one. Almost all of my incoming e-mails are HTML. This code leaves those completely unaffected.

Really? It made mine look like **** - the HTML was stripped leaving just a block of text.
I tried forwarding an HTML email to myself with the code switched on and off and now that I look at it more closely you are absolutely right. All the HTML code is stripped out.

So ideally what I would need would be code that tests to see if an incoming e-mail is HTML or not. If not, the existing code would run. If it is, ideally the HTML source code would be edited - I can see, I think, what needs to be deleted - or otherwise the macro would just end.

Is it possible to do something like this in the HTML source code using a VBA macro? Not that I would have a clue how to do it!
You can edit the source code as long it's always the same. You need to use the <p> parts too. Then use item.htmlbody = to put the body back.
How to Change the Font used for Outlook's RSS Feeds shows how to work with html code. Using the method on that page, it worked with HTML - if the string is long or has a line break, you might need to do it twice.

then you'd use if statements to check for the body format (or html code in the body string) and either use item.body or item.html body.

when the html code has double quotes " in it, you need to replace them with " & Chr(34) & "

If Item.BodyFormat = olFormatHTML Then

b = Item.HTMLBody
OldText = "<p style=" & Chr(34) & "font-size: 11px;color : #8a8a8a; text-align: center;margin: 10px;" & Chr(34) & ">If this email is not displaying correctly<br>"
NewText = ""
b = Replace(b, OldText, NewText, , , vbTextCompare)

OldText = "Please add <a href=" & Chr(34) & "" & Chr(34) & "><span style=" & Chr(34) & "color:#92171A; text-decoration:none" & Chr(34) & "></span></a> to your safe senders list. "
NewText = ""
b = Replace(b, OldText, NewText, , , vbTextCompare)

Item.HTMLBody = b
end if

If Item.BodyFormat = olFormatPlain Then

b = Item.Body
OldText = "If this email is not displaying correctly"
NewText = ""
b = Replace(b, OldText, NewText, , , vbTextCompare)

OldText = "Please add to your safe senders list. "
NewText = ""
b = Replace(b, OldText, NewText, , , vbTextCompare)

Item.Body = b
end if
Much to my surprise I managed to get this to work - sort of.

I added in declarations (is that the right name?):

Dim b$
Dim OldText$
Dim NewText$

before the first line of code in your last message, without which the code was not working.

Most incoming HTML e-mails now arrive with the text correctly deleted, but two have caused the macro to hang. I have no idea why. Plain text no longer seems to work as it did before. I suspect that is because of the code I added.

Is there some error trapping code I could use at least to stop the macro from hanging?
is there anything unique about the ones it fails on? do they have the string you are looking for in multiple times?

second half of the macro isn't working on plain text?
I cannot see anything unique at all. Having checked, the string I am looking for is not duplicated, although the first two words do form part of a different string. I would have thought that would not count.

You are right, the second half of the macro is not working on plain text.
is the case the same? Try using all lowercase in the oldtext string and
b = lcase(Item.Body)

remove any ending spaces.
What that does is to replace the old text with the same text all in lower case.
oh, shoot. forgot we then use b to set the item body. You'll need to make sure the oldtext is the proper case. Try it with no ending spaces and no line breaks - see if that removes the text part.
Not open for further replies.
Similar threads
Thread starter Title Forum Replies Date
D Delete selected text in outgoing email body Outlook VBA and Custom Forms 0
E Outlook 365 Save Selected Email Message as .msg File - oMail.Delete not working when SEARCH Outlook VBA and Custom Forms 0
R VBA Code to permanently delete selected email Outlook VBA and Custom Forms 10
mikolajek Random message selected after hard delete Using Outlook 4
B Delete Read Receipts in Your Outlook Outlook VBA and Custom Forms 0
A Outlook 365 Delete entries in title field, address book Using Outlook 0
D Delete Outlook emails from MS server Using Outlook 12
K How can I delete an e-mail from Outlook Using Outlook 1
G Automatically delete email when a condition is met Outlook VBA and Custom Forms 1
D Outlook 2021 Using vba code to delete all my spamfolders not only the default one. Outlook VBA and Custom Forms 0
M Shift Delete doesn't delete email from server Using Outlook 3
J Unable to delete folders in Outlook 2019 / Windows Using Outlook 0
Horsepower Cannot delete gmail in iPhone Outlook outbox Using Outlook 1
J Quick steps delete original email and move reply/sent email to folder Using Outlook 2
N How to add or delete items to Move dropdown Menu Using Outlook 0
G Automatically delete messages in the synchronization folder Outlook VBA and Custom Forms 3
O How to delete a forum post? Using Outlook 4
T Outlook 2010 Errore run-time -2147417851 (80010105) Metodo delete ContactItem non riuscito Outlook VBA and Custom Forms 0
C Outlook 2016 Unable to delete Gmail IMAP calendar Using Outlook 2
S Outlook 2016 dont delete inbox item Using Outlook 0
F Wishlist Outlook suddenly began synchronizing deleted items every time I delete a single email. Using Outlook 2
O Outlook 2010 Add delete button to the side of the message list Using Outlook 1
R Outlook 365 update sets delete from server flag Using Outlook 1
S Outlook 2016 A Shortcut to recall and delete and sent message. Using Outlook 1
T Outlook 2010 How to Delete “Orphaned” TO DO? ( Not on Exchange Server) Using Outlook 6
P How did hacker cause link to delete and archive containing email? Using Outlook 6
Z Outlook 365 delete reminder you can’t make change to contents of this-read only folder Using Outlook 4
J To delete the draft email Using Outlook 2
W Recurrence: delete older occurrences / change earliest start time Outlook VBA and Custom Forms 0
J Moved many emails to Outlook external folder, need to delete on Gmail server Using Outlook 14
A Attachments.Delete Outlook VBA and Custom Forms 3
R Help Revising VBA macro to delete email over different time span Outlook VBA and Custom Forms 0
R Expand VBA Permanent Delete Code Outlook VBA and Custom Forms 6
M Delete headers in Inline reply Outlook VBA and Custom Forms 5
N VBA to delete duplicates by message-id on common pst for 2 or more emails Outlook VBA and Custom Forms 0
S How can I delete all copies of a given companies logo graphic from all my emails at once? Using Outlook 3
9 Outlook 2016 How to save an Outlook attachment to a specific folder then delete the email it came from? Using Outlook 1
D after delete mail, open the next one Outlook VBA and Custom Forms 0
O Delete duplicate emails - subscription notifications Using Outlook 5
F Delete/create/reset Exchange mailbox on Using accounts in Outlook 3
L Email Read and Delete Outlook VBA and Custom Forms 4
H Delete Calendar Entries in Using Outlook 2
D Delete Emails from Senders in Shared Mailbox Outlook VBA and Custom Forms 1
R How to delete Facebook Contacts folder in Outlook 365 Using Outlook 7
JoeG Appointment Delete/Change Recurrence Outlook VBA and Custom Forms 0
C Outlook 2016 cannot delete, email showing in root Exchange Server Administration 5
C How to replace or delete first instance of sentence in mail body? Outlook VBA and Custom Forms 1
Z Can't delete IMAP folder Using Outlook 2
J Delete old emails Exchange Server Administration 1
undercover_smother Automatically Forward All Sent Mail and Delete After Send Outlook VBA and Custom Forms 10

Similar threads