How to delete a phrase from email? - vba

I'd like to remove the following phrase from the beginning of every email from sources other than a specific domain:
"This is an EXTERNAL email. Do not click links or open attachments unless you validate the sender and know the content is safe."
I am trying to delete this phrase from each email.
I grabbed some code online from another person trying to do something similar.
Sub Del()
Dim Ins As Outlook.Inspector
Dim Document As Word.Document
Dim Word As Word.Application
Dim Selection As Word.Selection
Set Ins = Application.ActiveInspector
Set Document = Ins.WordEditor
Set Word = Document.Application
Set Selection = Word.Selection
Dim search As String
search = "This is an EXTERNAL email. Do not click links or open attachments unless you validate the sender and know the content is safe."
Dim para As Paragraph
For Each para In Document.Paragraphs
Dim txt As String
txt = para.Range.Text
If InStr(txt, search) Then
para.Range.Delete
End If
Next
End Sub
I get
Run-time error '91'
on line 9 Set Document.

that works a lot easier within Outlook:
sub delete_part_of_text()
Dim search As String
search = "This is an EXTERNAL email. Do not click links or open attachments unless you validate the sender and know the content is safe."
If Not TypeOf Item Is mailitem Then Exit Sub
Item.HTMLBody = Replace(Item.HTMLBody, search, "")
end sub
of course you have to adapt this - should this run automatically on each incoming mail oder are you going to call this when needed for one/some mails? That changes the call of the procedure, but the princip abobe works.
Max

Related

Create a rule that deletes attachments before forwarding

I have been tasked to create an automated report system where an report from Google Data Studios are uploaded to specific projects (On a site called Basecamp). The reports always include both a report within the body of the e-mail and an attached PDF file. The are sent to a Gmail account (data studios refuse to schedule towards a non-Google account). The filters within Gmail doesnt really work well with the Basecamp system so I use filters to re-route them towards a Outlook account. There I use rules to send each e-mail towards the correct client within Basecamp.
Here comes the problem, Basecamp shows both the body of the e-mail AND the attached PDF version which makes us show duplicates.
Is there a way to create a macro that first deletes all attachments (or body of an e-mail) and THEN forward the e-mail.
It cant be done manually it have to be a rule that does it automaticaly. Keep in mind that I am not a coder and have never done anything like this so please keep it simple for my dumb brain!
Thank you in advance!
Marcus
PS: I found a code that seems to be what I am after.
Public WithEvents ReceivedItems As Outlook.Items
Private Sub Application_Startup()
Set ReceivedItems = Outlook.Application.Session.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub ReceivedItems_ItemAdd(ByVal Item As Object)
Dim xForwardMail As Outlook.MailItem
Dim xEmail As MailItem
On Error Resume Next
If Item.Class <> olMail Then Exit Sub
Set xEmail = Item
If InStrRev(UCase(xEmail.Subject), UCase("kto feature")) = 0 Then Exit Sub 'change subject text to your need
If xEmail.Attachments.Count = 0 Then Exit Sub
Set xForwardMail = xEmail.Forward
With xForwardMail
.HTMLBody = ""
With .Recipients
.Add "skyyang#addin88.com" 'change address to your own
.ResolveAll
End With
.Send
End With
End Sub
I am trying to get that code to work, and changes the subject to a specific word and then route it to a final e-mail account that then filters out to correct clients. However the code doesnt seem to work, it DOES forward the e-mail but the attachment is still there. The code was found at https://www.extendoffice.com/documents/outlook/5359-outlook-forward-attachment-only.html#a1
It seems you need to modify the code slightly:
Public WithEvents ReceivedItems As Outlook.Items
Private Sub Application_Startup()
Set ReceivedItems = Outlook.Application.Session.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub ReceivedItems_ItemAdd(ByVal Item As Object)
Dim xForwardMail As Outlook.MailItem
Dim xEmail As MailItem
Dim myattachments as Outlook.Attachments
On Error Resume Next
If Item.Class <> olMail Then Exit Sub
Set xEmail = Item
If InStrRev(UCase(xEmail.Subject), UCase("kto feature")) = 0 Then Exit Sub 'change subject text to your need
If xEmail.Attachments.Count = 0 Then Exit Sub
Set xForwardMail = xEmail.Forward
Set myattachments = xForwardMail.Attachments
While myattachments.Count > 0
myattachments.Remove 1
Wend
With xForwardMail
.HTMLBody = ""
With .Recipients
.Add "skyyang#addin88.com" 'change address to your own
.ResolveAll
End With
.Send
End With
End Sub
The Remove method of the Attachments class removes an object from the collection.

Outlook Email created in VBA using a template converts to plain text when saved

Below is the code that I am running in ThisOutlookSession. The code is meant to check all incoming emails and if the email is from a certain email address and contains a specific string in the subject then a new email is created from a template and the triggering email is attached and the email is then sent out to a different email address. This portion all works fine.
Also to note I am using windows 10 and office 2016.
The problem that I am having is the email is converted to plain text unless it is displayed first. The template that I have created is saved as a HTML formatted message. I have tried adding lines such as
NewMsg.BodyFormat = olFormatHTML
NewMsg.save
But this doesn't seem to work as the email that is sent was still in the plain text format. If I add the following to that the message it basically works.
NewMsg.BodyFormat = olFormatRichText
NewMsg.save
NewMsg.BodyFormat = olFormatHTML
NewMsg.save
However the above block of code removes a lot of the formatting that was saved in my template such as different fonts/ font sizes.
Am I missing something about working with templates in VBA?
Also The problem that I am having with displaying the message first is two things. The obvious one is the flash that this causes because the message is briefly displayed. The second is my default signature is also added to the displayed message but I wanted to use a custom signature that I built into my template.
Here is my full code with sensitive information removed.
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
' default local Inbox
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error GoTo ErrorHandler
Dim Msg As Outlook.MailItem
Dim NewMsg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
If Msg.SenderEmailAddress <> "example#example.com" Then GoTo Skip
If InStr(1, Msg.Subject, "Specific String") > 0 Then 'checks if subject contains the proper string
Set NewMsg = Application.CreateItemFromTemplate("Template Path")
Msg.Subject = Replace(Msg.Subject, "Old Subject", "New subject")
Msg.Save
NewMsg.HTMLBody = NewMsg.HTMLBody
NewMsg.Attachments.Add Msg
NewMsg.Recipients.Add("Example#Example.com")
NewMsg.Subject = Msg.Subject
NewMsg.Save
NewMsg.Send
End If
End If
Skip:
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
End Sub
Reset the HTMLBody property - that will force HTML format:
Msg.HTMLBody = Msg.HTMLBody

Selecting Outlook Emails to Paste to Word Document - VBA Macro

I want to:
Select all emails from a certain sender
Copy the body of the email to a new Word document
Save the word document to a specific directory
Clear the clipboard
I'd like to know what else I need to do, especially in the the FindSetAside() and SaveToDicrectory() functions.
Sub FindSetAside() 'find all set-aside emails
End Sub
Sub PasteToWord()
Dim Word As Word.Application
Dim Doc As Word.Document
Dim activeMessage As Outlook.MailItem 'the email to copy
Dim activeBody As String
If TypeName(ActiveExplorer.Selection.Item(1)) = "MailItem" Then
'get the active email
Set activeMessage = ActiveExplorer.Selection.Item(1)
'setup Word
Set Word = CreateObject("Word.Application")
WordApp.Visible = True
setDoc = Word.Documents.Add
'Copy selection to document
activeMessage.GetInspector().WordEditor.Range.FormattedText.Copy
Doc.Range.Paste
Call ClearClipboard
End If
End Sub
Sub SaveToDirectory() 'Save the Word Document to the correct directory
End Sub
Public Sub ClearClipboard()
Dim Data As New DataObject
Data.SetText Tex:=Empty
Data.PutInClipboard
End Sub
I am using Outlook 2010. I am also considering adding some code to send the Word document as an attachment to specific emails, but perhaps that is irrelevant to this question.
Using Explorer.Selection won't help if you need to execute a search for certain emails (unless you use Explorer.Search, which executes a search in the UI). Take a look at this to help determine the search method you need to use:
https://msdn.microsoft.com/EN-US/library/ff869846.aspx
Then it is just a matter of traversing the returned collection and accessing the MailItem objects within.
To save the Word document, use Document.SaveAs2.

Delete Signature from email with VBA

I am currently in the process of anonymizing emails with vba for a project.
Currently when an email is received I have created a rule which moves the email into a folder, thereafter I run a script using the getlast function, in that specific folder, where I display the newly received email and copy the content of the email and then i paste this into a new email and send to a particular email address. This effectively removes the identifying features of the email.
The final movement to the Rubik's Cube is to find the email signature and replace with blank, in other words delete the signature. I will have the email signatures to do this, however it would be great if someone someone could help with this...
I found this solution.
'I also had to add Word in tools/references of VBA and then Call DeleteSig(msg) after displaying the item.
'http://www.access-programmers.co.uk/forums/showthread.php?t=259417
Sub DeleteSig(msg As Outlook.MailItem)
Dim objDoc As Word.Document
Dim objBkm As Word.Bookmark
On Error Resume Next
Set objDoc = msg.GetInspector.WordEditor
Set objBkm = objDoc.Bookmarks("_MailAutoSig")
If Not objBkm Is Nothing Then
objBkm.Select
objDoc.Windows(1).Selection.Delete
End If
Set objDoc = Nothing
Set objBkm = Nothing
End Sub
It's not very hard, but depend on some properties of the mail:
Is the mail plain text? or html
if HTML, do you have the signature in html format ? (with tags)
I presume you read your mail with a variable of type Outlook.MailItem
' Definition of your mail
Dim OutMail As Outlook.MailItem
dim signature as string
...
with OutMail
.HTMLBody = Replace(.HTMLBody, signature, "")
End with
If the signature you have is not the exact match, it'll be a little more tricky.
I suggest to create a function that detect the signature and return the HTMLBody without it

Read body of email with attachment using VBA in Outlook

I have some VBA that checks the subject of every message as soon as it hits my inbox, and submits certain emails' contents over http to a server for processing.
This works great for messages with no attachments, but fails if there is an attachment on the email. I am using a http GET to submit the text.
What is the effect of the presence of an attachment on the body property of the message, and how can I ignore the attachment and submit only the email body text?
The VBA (trimmed for clarity but complete and functional):
Declarations:
Option Explicit
Private WithEvents olInboxItems As Items
On startup:
Private Sub Application_Startup()
Set olInboxItems = Session.GetDefaultFolder(olFolderInbox).Items
End Sub
On item added to inbox:
Private Sub olInboxItems_ItemAdd(ByVal Item As Object)
On Error Resume Next
Dim olMailItem As MailItem
Dim strAttachmentName As String
Dim submitResult As String
If TypeOf Item Is MailItem Then
Set olMailItem = Item
If ((InStr(olMailItem.subject, "test subject") > 0)
Dim subject As String
subject = olMailItem.subject
Dim contents As Variant
contents = olMailItem.body
Dim submitURL As String
submitURL = "http:// ... " & subject & "..." & contents & "..."
XMLHttpSynchronous submitURL
End If
End If
Set Item = Nothing
Set olMailItem = Nothing
End Sub
Http submit:
Sub XMLHttpSynchronous(ByVal URL As String)
Dim XMLHttpRequest As XMLHTTP
Set XMLHttpRequest = New MSXML2.XMLHTTP
XMLHttpRequest.Open "GET", URL, False
XMLHttpRequest.Send
End Sub
edit: I am now stripping attachments with the below code (tested and working) but the url still isn't submitting correctly.
Set myattachments = olMailItem.Attachments
While myattachments.Count > 0
myattachments.Remove 1
Wend
edit 2: I set contents=subject and the url submitted correctly, still no luck with the email's body, even after the message has been stripped of attachments
In order to get this working I stripped the attachments with the code in my first edit, than split the string of the body's text around the first and last character. I'm not sure why this works