Find and delete specific sentence in first line of emails - vba

All my emails have this sentence added " this email has come from an external source. Do not click on links or open attachments unless you recognise the sender."
I would like to delete it.; I have made this macro but it does not work. Nothing happens. Other macros do work in outlook session, so it is not a security issue. I would expect the macro to take a minute or so for 100s of emails to search. but nothing happens at all. Can you help ?
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
'MsgBox (K)
For i = 1 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).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

There is no need to open the mailitems.
Option Explicit
Sub RemoveExpressionFOLDER()
Dim outFldr As folder
Dim outItems As Items
Dim outMailItem As MailItem
Dim i As Long
Dim cleanCount As Long
Set outFldr = ActiveExplorer.CurrentFolder
Set outItems = outFldr.Items
For i = 1 To outItems.Count
If outItems(i).Class = olMail Then
Set outMailItem = outItems(i)
With outMailItem
'Debug.Print .Subject
If InStr(.Body, "THINK SECURE. This email has come from an external source. Do not click on links or open attachments unless you recognise the sender.") Then
If .BodyFormat = olFormatHTML Then
.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.", "")
Else
.Body = Replace(.Body, "THINK SECURE. This email has come from an external source. Do not click on links or open attachments unless you recognise the sender.", "")
End If
.SAVE
cleanCount = cleanCount + 1
End If
End With
End If
Next i
MsgBox (cleanCount & " mailitems cleaned.")
End Sub

Related

Redemption-Outlook VBA Script to move mails with attached msg file from certain sender

I am trying to write a VB script for Outlook with Redemption. My task is as follows :
Cycle through all emails in my inbox
Examine each mail as I go through them
If it has an attachment I want to inspect further
If the attachment is a msg file and it is from a certain sender then move it to a specific folder
I have determined that Redemption would be the easiest to use as it allows you to inspect attachment without having to save them and open them. I have the following working which will tell me the information for the selected emails attached message.
Sub GetAttachmentInfo()
Dim olApp As Outlook.Application
Set olApp = CreateObject("Outlook.Application")
Dim olNS As Outlook.NameSpace
Set olNS = olApp.GetNamespace("MAPI")
Dim FolderSrc As MAPIFolder
Set FolderSrc = CreateObject("Outlook.Application"). _
GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Dim oRDOSession As Redemption.RDOSession
Set oRDOSession = CreateObject("Redemption.RDOSession")
oRDOSession.MAPIOBJECT = olNS.Application.Session.MAPIOBJECT
Set Inbox = oRDOSession.GetDefaultFolder(olFolderInbox)
Set Mail = olApp.ActiveExplorer.Selection.Item(1)
Debug.Print "EntryID: " & Mail.EntryID
Set Mail = oRDOSession.GetMessageFromID(Mail.EntryID)
For Each Msg In FolderSrc.Items
For Each att In Mail.Attachments
Debug.Print "Sender: " & att.EmbeddedMsg.SenderEmailAddress
Debug.Print "Embedded Msg Subject: " & att.EmbeddedMsg
Next
Next
End Sub
I haven't found a way to adopt this to move through every item in my inbox. But have been able to cycle through emails in my inbox to get the subject line.
Sub subjectLine()
Dim olApp As Outlook.Application
Set olApp = CreateObject("Outlook.Application")
Dim Folder As Object
Dim olNS As Outlook.NameSpace
Set olNS = olApp.GetNamespace("MAPI")
Dim oRDOSession As Redemption.RDOSession
Set oRDOSession = CreateObject("Redemption.RDOSession")
oRDOSession.MAPIOBJECT = olNS.Application.Session.MAPIOBJECT
Set Folder = Session.GetDefaultFolder(olFolderInbox)
For Each Msg In Folder.Items
Debug.Print (Msg.Subject)
Next
End Sub
I know that the basic idea is just a
For Each Mail in Inbox.Items
If Mail.Attachment >0
If attachment.sender = "whoever"
Move to "Specific Folder"
End If
End If
Next
Can someone advise on how to do this?
In your first script you are already looping through all items in the Inbox, but you never touch them - you are continuously processing the attachment's of the selected message. In the line
For Each att In Mail.Attachments
replace Mail with Msg. You will also need to make sure that you are touching an embedded message attachment. Off the top of my head:
For Each Msg In FolderSrc.Items
For Each att In Msg .Attachments
if att.Type = 5 Then 'olEmbeddedItem
set embeddedMsg = att.EmbeddedMsg
Debug.Print "Sender: " & embeddedMsg.SenderEmailAddress
Debug.Print "Embedded Msg Subject: " & embeddedMsg.Subject
End If
Next
Next

How to send a Word document as body of an email with VBA

I've created a macro that works with outlook and excel that will use a list of email addresses (in excel) and send all those addresses an email (in outlook). I want to take a word document (from microsoft word) and use it as the body of the email. The problem is, I will have images in the word document and I need the word document to keep it's formatting. Right now, my VBA takes the content of my word document but the formatting is gone and images aren't included. This is my code:
Sub spamEmail()
'Setting up the Excel variables.
Dim olApp As Object
Dim oMail As Outlook.MailItem
Dim iCounter As Integer
Dim Dest As Variant
Dim SDest As String
Dim Excel As Object
Dim Name As String
Dim Word As Object
Dim oAccount As Outlook.Account
Dim doc As Word.Document
Dim itm As Object
Dim MsgTxt As String
'Set the outlook account to send.
Set oAccount = Application.Session.Accounts.Item(2)
'Create excel object.
Set Excel = CreateObject("excel.application")
Excel.Visible = True
Excel.Workbooks.Open ("C:\Users\Deryl Lam\Documents\Book1.xlsx")
Excel.Workbooks("Book1.xlsx").Activate
'Create a word object.
Set Word = CreateObject("word.application")
Set doc = Word.Documents.Open _
(FileName:="C:\Users\Deryl Lam\Documents\emailBody.docx", ReadOnly:=True)
'Pulls text from file for message body
MsgTxt = doc.Range(Start:=doc.Paragraphs(1).Range.Start, _
End:=doc.Paragraphs(doc.Paragraphs.Count).Range.End)
'Loop through the excel worksheet.
For iCounter = 1 To WorksheetFunction.CountA(Workbooks("Book1.xlsx").Sheets(1).Columns(1))
'Create an email for each entry in the worksheet.
Set oMail = Application.CreateItem(olMailItem)
With oMail
SDest = Cells(iCounter, 1).Value
If SDest = "" Then
'Dont do anything if the entry is blank.
Else
'Do additional formatting on the BCC and Subject lines, add the body text from the spreadsheet, and send.
Name = Cells(iCounter, 2).Value
.BCC = SDest
.Subject = "FYI"
.Body = "Dear " & Name & "," & vbCrLf & MsgTxt
'SendUsingAccount is new in Office 2007
'Change Item(1)to the account number that you want to use
.SendUsingAccount = oAccount
.Send
End If
End With
Next iCounter
'Clean up the Outlook application.
Set olMailItm = Nothing
Set olApp = Nothing
End Sub
I've searched all over google for a solution but I haven't found one. How can I send a word document as the body of the email with it's formatting in tact and the images included?
You are getting the contents of your template document as a string, which by definition will not contain any formatting or images. You should instead copy the contents to the clipboard and then paste them into the new email.
Something like this:
Sub emailFromDoc()
Dim wd As Object, editor As Object
Dim doc As Object
Dim oMail As MailItem
Set wd = CreateObject("Word.Application")
Set doc = wd.documents.Open(...path to your doc...)
doc.Content.Copy
doc.Close
set wd = Nothing
Set oMail = Application.CreateItem(olMailItem)
With oMail
.BodyFormat = olFormatRichText
Set editor = .GetInspector.WordEditor
editor.Content.Paste
.Display
End With
End Sub
If not for the images, you could save the document as an HTML file, read its contents, then set the MailItem.HTMLBody property.
Images are more involved. I don't see a straightforward way to bring them into a message body.

Getting attachment from Outlook and placing in the body of a new Email after Formatting

This is essentially what I am trying to do...
search for a specific email by subject name
get the attachment to that email ( the attachment is an excel sheet of raw data)
run a formatting subroutine from another module on the excel attachment
place the newly formatted attachment to the body of a new email
Send the new email out to the client
I need help with steps 3 & 4.
Option Explicit
Sub sendEmail()
Dim olApp As Outlook.Application
Dim olEmail As Outlook.MailItem
Dim olNs As Namespace
Dim Fldr As MAPIFolder
Dim olMi As MailItem
Dim olAtt As Attachment
Dim MyPath As String
Dim i As Long
Set olApp = New Outlook.Application
Set olEmail = olApp.CreateItem(olMailItem)
Set olNs = olApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderInbox)
MyPath = "C:\Users\(Me)\Desktop\"
For i = Fldr.Items.count To 1 Step -1
Set olMi = Fldr.Items(i)
If InStr(1, olMi.Subject, "[The email I'm looking for by subject]") > 0 Then
For Each olAtt In olMi.Attachments
olAtt.Module2.Format '<--- this is where i try to do step 3
olAtt.SaveAsFile MyPath & "NewSheet" & ".xls"
With olEmail
.BodyFormat = olFormatHTML
.Body = olAtt.Range '<----this is where i try to do step 4
.To = "someone#something.com"
.Subject = "Tester"
.send
End With
Next olAtt
olMi.Save
End If
Next i
Set olAtt = Nothing
Set olMi = Nothing
Set Fldr = Nothing
Set MoveToFldr = Nothing
Set olNs = Nothing
Set olApp = Nothing
End Sub
See Getting Started with VBA in Outlook 2010.
I have noticed the following code:
For i = Fldr.Items.count To 1 Step -1
Set olMi = Fldr.Items(i)
If InStr(1, olMi.Subject, "[The email I'm looking for by subject]") > 0 Then
Do not iterate over all items in the folder. Instead, you need to use the Find/FindNext or Restrict methods of the Items class to get items which corresponds to your conditions. You can read more about them in the following articles in MSDN. Also you may find the following articles helpful:
How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)
How To: Use Restrict method to retrieve Outlook mail items from a folder
.Body = olAtt.Range '<----this is where i try to do step 4
The Outlook object model provides three main ways for working with item bodies:
Body.
HTMLBody.
The Word editor. The WordEditor property of the Inspector class returns an instance of the Word Document which represents the message body. So, you can use the Word object model do whatever you need with the message body.
See Chapter 17: Working with Item Bodies for more information.

Delete automatic Signature from forwarded emails VBA macro

Newbie Outlook VBA. intermediate Excel VBA. Windows 7 Professional, Outlook 2010
I have a script running from a rule that autoforwards all incoming emails. I need it as a rule because otherwise it will not forward the mails in the queue when Outlook loads.
I would like to have the default signature deleted when the mails are forwarded. As the reply is "blank" it is unnecessary to have the sig appended. I have found some code that supposedly worked in Outlook 2007 from the MSDN site. It compiles no errors, executes no errors. I have referenced MS Word in VBA. But the forwarded emails all have the signature still attached.
I cannot just delete the signature because I need it to be there on replies. The switch for the signature is for both replies and forwarded mail.
Here is the code:
Option Explicit
Sub Incoming3(MyMail As MailItem)
Dim strID As String
Dim strSender As String
Dim StrSubject As String
Dim objItem As Outlook.MailItem
Dim myItem As Outlook.MailItem
strID = MyMail.entryID
Set objItem = Application.Session.GetItemFromID(strID)
strSender = objItem.SenderName
StrSubject = objItem.Subject
StrSubject = strSender + ": " + StrSubject
objItem.Subject = StrSubject
objItem.AutoForwarded = False
Set myItem = objItem.Forward
myItem.Recipients.Add "bcc.hwb#gmail.com"
myItem.DeleteAfterSubmit = True
Call DeleteSig(objItem)
myItem.Send
Set myItem = Nothing
Set objItem = Nothing
End Sub
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
Any help with Outlook or VBA code would be much appreciated.
Processing the wrong mail in DeleteSig.
myItem.DeleteAfterSubmit = True
Call DeleteSig(myItem)
myItem.Send
Edit 2015 02 26
Debugging VBA Code
Private Sub Incoming3_test()
' Open a mailitem then click F8 repeatedly from this code
Dim currItem As MailItem
Set currItem = ActiveInspector.currentItem
Incoming3 currItem
End Sub
Sub Incoming3(MyMail As MailItem)
Dim myItem As Outlook.MailItem
Set myItem = MyMail.Forward
myItem.Subject = MyMail.senderName & ": " & MyMail.Subject
myItem.Recipients.Add "bcc.hwb#gmail.com"
myItem.DeleteAfterSubmit = True
myItem.Display ' If you are using F8 you can
' view the action taken in DeleteSig.
' Delete the line later.
Call DeleteSig(myItem)
'myItem.Send
Set myItem = Nothing
End Sub
Sub DeleteSig(msg As Outlook.MailItem)
Dim objDoc As Word.Document
Dim objBkm As Word.Bookmark
On Error Resume Next '<--- Very bad without On Error GoTo 0
Set objDoc = msg.GetInspector.WordEditor
Set objBkm = objDoc.Bookmarks("_MailAutoSig")
On Error GoTo 0
If Not objBkm Is Nothing Then
objBkm.Select ' <--- This is where the action starts.
objDoc.Windows(1).Selection.Delete
End If
Set objDoc = Nothing
Set objBkm = Nothing
End Sub
Edit 2015 02 26 - End
When you assign a VBA macro sub to run by the rule you get an instance of the MailItem object. For example:
Sub Incoming3(MyMail As MailItem)
The MyMail object represents an incoming email message which you should use in the code. But I see that you get a new instance:
strID = MyMail.entryID
Set objItem = Application.Session.GetItemFromID(strID)
There is no need to do so. Use the MyMail object in the code.
Also I see the following code:
Set objBkm = objDoc.Bookmarks("_MailAutoSig")
Try to run the code under the debugger and see whether the bookmark can be found. If there is no such bookmark you need to search the body for the first entry From: in the text and delete all the content before that keyword.
Finally, you may find the Getting Started with VBA in Outlook 2010 article in MSDN helpful.

How to forward emails in a folder and change the reply to address to the original sender?

I have a user who wants to redirect any email to other people in their department so that when that person replies to the email it will go back to the person who originally sent it.
I am trying to make VBA code to forward all emails in a specified folder and change the reply to address so that they don't have to manually put it in every time.
Sub SendFolder()
Dim olApp As Outlook.Application
Dim olNS As Outlook.NameSpace
Dim MyFolder As Outlook.MAPIFolder
Dim ObjMail As Outlook.MailItem
Set olApp = Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")
Set MyFolder = Application.Session.Folders("me#us.com").Folders("test")
For i = MyFolder.Items.Count To 0 Step -1
Set ObjMail.Subject = MyFolder.Itmes(i).Subject
Set ObjMail.ReplyRecipients = MyFolder.Itmes(i).ReplyRecipients
Set ObjMail.Body = MyFolder.Itmes(i).Body
Set ObjMail.Attachments = MyFolder.Itmes(i).Attachments
Set ObjMail.BodyFormat = MyFolder.Itmes(i).BodyFormat
Set ObjMail.To = "test#us.com"
ObjMail.Send
Next
End Sub
You are missing
Set ObjMail = Application.CreateItem(olMailItem)
Then your code would become
With ObjMail
.Subject = MyFolder.Itmes(i).Subject
.ReplyRecipients = MyFolder.Items(i).ReplyRecipients
.Body = MyFolder.Items(i).Body
.Attachments = MyFolder.Items(i).Attachments
.BodyFormat = MyFolder.Items(i).BodyFormat
.To = "test#us.com"
.Send
End with
It it runs now, the ReplyTo does not change.
You will want to set the ObjMail's ReplyRecipients property
Something like .ReplyRecipients.Add MyFolder.Items(i).SenderEmailAddress
To simplify the issue, .Forward the mail as is, and set only the ReplyRecipients property.
Check out this alternative. The mail is sent as an attachment. The receiver automatically replies to the original sender.
Untested
Sub SendFolderItemsAsAttachments()
' Run this VBA code while in Outlook
Dim MyFolder As MAPIFolder
Dim notMyItems as Items
Dim notReplyingToMe as mailitem
Dim i as long
Set MyFolder = Application.Session.Folders("me#us.com").Folders("test")
Set notMyItems = MyFolder.Items
For i = notMyItems.Count To 1 Step -1
If TypeOf notMyItems(i) Is MailItem Then
Set notReplyingToMe = Application.CreateItem(olMailItem)
With notReplyingToMe
.Subject = notMyItems(i).Subject & " - " & _
notMyItems(i).SenderName
.HTMLBody = "Redirecting for your action."
.Attachments.Add notMyItems(i), olEmbeddeditem
.To = "test#us.com"
.Send
End With
notMyItems(i).Delete
End If
Next
Set MyFolder = = Nothing
Set notMyItems = Nothing
Set notReplyingToMe = Nothing
End Sub